views:

697

answers:

1

I have this code:

      <Grid x:Name="LayoutRoot">
   <Grid HorizontalAlignment="Left" Height="900" Width="1200">
   <Grid.RowDefinitions>
            <RowDefinition Height="300"></RowDefinition>
            <RowDefinition Height="200"></RowDefinition>
            <RowDefinition Height="200"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="300"></ColumnDefinition>
            <ColumnDefinition Width="300"></ColumnDefinition>
            <ColumnDefinition Width="300"></ColumnDefinition>
            <ColumnDefinition Width="300"></ColumnDefinition>
        </Grid.ColumnDefinitions>
    <ListBox x:Name="lst1" Width="300" Height="100" Grid.Row="0" Grid.Column="0">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal" Margin="3">
                            <TextBlock Text="Id:" Foreground="Brown"></TextBlock>
                            <TextBlock Text="{Binding Id}" Foreground="Blue"></TextBlock>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
  </ListBox>
  <ListBox x:Name="lst1" Width="300" Height="100" Grid.Row="0" Grid.Column="1"/>
  <ListBox x:Name="lst2" Width="300" Height="100" Grid.Row="0" Grid.Column="2"/>
  <ListBox x:Name="lst3" Width="300" Height="100" Grid.Row="0" Grid.Column="3"/>
  </Grid>
    </Grid>

How can I create a DataTemplate/ItemTemplate in the code behind with Silverlight?

A: 

To create a DataTemplate dynamically you need to build the Xaml string that describes it using XML manipulation objects such as XDocument or XmlTextWriter. The root of this Xaml needs to be the DataTemplate itself (remember to include or the correct namespaces).

You can then pass the resulting string XamlReader.Load which will create the DataTemplate which you then assign to the ItemTemplate property of the ListBox.

AnthonyWJones