#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}">
            <Border BorderThickness="2" BorderBrush="DarkBlue">
                <StackPanel Orientation="Vertical">
                    <StackPanel Orientation="Horizontal">
                        <Label Content="{Binding Path=FirstName}"/>
                        <Label Content="{Binding Path=LastName}" FontWeight="Bold"/>
                    <Label Content="{Binding Path=BirthYear}" FontStyle="Italic"/>

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

  <ListBox Margin="15" Width="270" Height="320"
         ItemsSource="{Binding ActorList}">
                <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"/>
                    <Label Content="Dead Fred !" Foreground="Red"
                           Visibility="{Binding Converter={StaticResource deadFredConverter}}"/>