Xam IWriter Xam IReader

In the chapters 4 and 5, covering dynamic Win and WebForms, respectively, you examined how to iterate the Controls collection to produce an XML image of the Form's hierarchy. With WPF, an XML image is part and parcel of the technology itself. XAML is XML that defines your Window as you create it with the visual designer. Just as WinForms and WebForms applications generate the source code to instantiate, initialize, and position the controls you draw on them, WPF does the same via XAML. No source code is generated when Windows are visually designed—only XAML. Because the screen layout is stored in an XML format already, you can design your forms and then store the XAML in a database for later retrieval.

Visual Studio provides two classes from the System.Windows.Markup namespace to handle this for you: XamlWriter and XamlReader. Suppose you wish to persist the layout of the Window shown in Figure 6-11. You can extract the XAML and save it to a file as follows:

string szXAML = XamlWriter.Save(this.Content);

File.WriteAllText(@"c:\temp\griddemo.xaml", szXAML);

The XAML looks like Listing 6-14.

Listing 6-14. XAML for Window Layout

<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:s="clr- namespace:System;assembly=mscorlib"> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions>

<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions>

<Label Grid.Column="0" Grid.Row="0">Last Name:</Label> <TextBox Name="txtLastName" Width="100" Grid.Column="1"

Grid.Row="0" xml:space="preserve" /> <Label Grid.Column="0" Grid.Row="1">Salutation:</Label> <ComboBox Name="cmbSalutation" Width="100" Grid.Column="1" Grid.Row="1"> <s:String>Mr.</s:String> <s:String>Mrs.</s:String> <s:String>Dr.</s:String> </ComboBox>

<Button Width="100" Grid.Column="1" Grid.Row="2">Get Data</Button> </Grid>

To re-create a window from this data, you can use the XamlReader as shown in Listing 6-15.

Listing 6-15. Recreating a Window from XAML Using XamlReader string szXAML = File.ReadAllText(@"c:\temp\griddemo.xaml"); this.Content = XamlReader.Parse(szXAML);

0 0

Post a comment