#1,183 – Where Data Templates Are Used

Data templates dictate how bound data is mapped to one or more control.  A data template can be used in two places:

  • As value of ContentTemplate property for a ContentControl  (e.g. a Label)
  • As value of ItemTemplate property for an ItemsControl  (e.g. a ListBox)

Here’s an example of a DataTemplate used as the ContentTemplate for a Label:

<Label Name="lblPerson" Content="{Binding}">
    <Label.ContentTemplate>
        <DataTemplate>
            <Border BorderThickness="2" BorderBrush="DarkBlue">
                <StackPanel Orientation="Vertical">
                    <StackPanel Orientation="Horizontal">
                        <Label Content="{Binding Path=FirstName}"/>
                        <Label Content="{Binding Path=LastName}" FontWeight="Bold"/>
                    </StackPanel>
                    <Label Content="{Binding Path=BirthYear}" FontStyle="Italic"/>
                </StackPanel>
            </Border>
        </DataTemplate>
    </Label.ContentTemplate>
</Label>

Here’s an example of a DataTemplate used as the ItemTemplate for a ListBox:

  <ListBox Margin="15" Width="270" Height="320"
         ItemsSource="{Binding ActorList}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Image Source="{Binding Image}" Height="80"/>
                    <StackPanel Margin="5">
                        <TextBlock Text="{Binding FullName}" FontSize="12" FontWeight="Bold"/>
                        <TextBlock Text="{Binding Dates}"/>
                        <TextBlock Text="{Binding KnownFor}" Margin="0,5,0,0" FontStyle="Italic"/>
                    </StackPanel>
                    <Label Content="Dead Fred !" Foreground="Red"
                           FontWeight="Bold"
                           Visibility="{Binding Converter={StaticResource deadFredConverter}}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
Advertisements