Listing B3 Dynamic Grid with Templates

<Page x:Class="CustomersViewerXAML.Page1" xmlns="http://schemas. microsoft, co m/winfx/avalon/2005" xmlns:x="http://schemas. microsoft, co m/winfx/xaml/2005"


<Page.Resources> </Page. Resources>

<Grid HorizontalAlignment-'Left" VerticalAlignment="Top"> <ColumnDefinition Width="400" /> <RowDefinition Height="50"/> <RowDefinition /> <Grid Grid.Row="0"> <ColumnDefinition Wdth="100*" /> <ColumnDefinition Wdth="100*" /> <ColumnDefinition Wdth="100*" /> <TextBlock Grid.Column="0">Company</TextBlock> <TextBlock Grid.Column="1 ">Contact</TextBlock> <TextBlock Grid.Column="2">Phone</TextBlock> </Grid>

<ltemsControl Grid.Row="1" Margin="20,0,20,20"

ltemsSource="{Binding}"> <ltemsControl.ltemTemplate> <DataTemplate> <Grid>

<ColumnDefinition Width="100*" /> <ColumnDefinition Width="100*" /> <ColumnDefinition Width="100*" /> <TextBox Text="{Binding Path=CompanyName}"

Grid.Column="0" /> <TextBox Text="{Binding Path=ContactName}"

Grid.Column="1" /> <TextBox Text="{Binding Path=Phone}" Grid.Column="2" />

</Grid> </DataTemplate> </ltemsControl.ltemTemplate>

In Listing B.3. the ItemTemplate is defined under theltemsControl. The ItemsControl is bound to the default data context, which gets set in the code-behind on page load as described shortly. What happens is that for each item in the bound collection, an instance of the contents of the DataTemplate gets injected into theltemsControl. So this creates an instance of aGrid, with its content controls each bound to the appropriate part of the current item, rendered for each row in the data source.

The data context in this sample is set to a data set of customers through thePageLoaded event handler:

private void PageLoaded(object sender, EventArgs e) {

SqIConnection conn = new SqlConnection( "server=localhost;database=Northwind;trusted_connection=true"); SqIDataAdapter adapter = new SqlDataAdapter( "SELECT* FROM Customers", conn); DataSet ds = new DataSet(); adapter.Fill(ds, "Customers"); DataContext = ds.Tables["Customers"].DefaultView;

Templates in XAML allow you to specify the shape of the content that is rendered for individual items in a control collection. The controls can be rendered based on data items in a collection as was done here. This gives you a lot of flexibility for dynamically constructing a form based on bound data.


0 0

Post a comment