8 Data templates
A data template is more important in XAML markup, which defines how the bound object is displayed. A total of two types of controls support data templates:
1 The content control (the control with the Content property) supports the data template through the ContentTemplate property. Used to show anything you put in the content attribute.
2 The list control (a control inherited from ItemsControl) supports data binding through the ItemTemplate property. This template is used to display each item in the collection (the collection of objects you provide to the ItemsSource attribute).
List templates are based on content templates, like the Listboxitem,combobox ComboBoxItem of a ListBox, and so on. No matter what itemtemplate you use, you can still use ContentTemplate for each item.
<ListBox >
<ListBox.ItemTemplate>
<DataTemplate>
<ScrollViewer>
<TextBlock Text="{Binding Name}"></TextBlock>
</ScrollViewer>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
When you bind products together to a ListBox (by setting ItemsSource), each ListBoxItem is a product object. The Listboxitem.content property is set to an Product object, listboxitem.contenttemplate to control the display of the data, which is bound to the product name.
8.1 Detach Reuse Template
Like styles, templates are usually defined at the page or application level, rather than on a list. Separation is usually better, especially if your template is long, complex, or uses multiple templates on a single control. At the same time you can also unify your interface style, can use this template everywhere.
To do this, you need to define and give it a unique name in the Resources collection collection. The following defines a template resource
Code
<UserControl.Resources >
<DataTemplate x:Key="ProductDataTemplate">
<Border Margin="5" BorderThickness="1" BorderBrush="SteelBlue" CornerRadius="5">
<Grid Margin="3">
<Grid.RowDefinitions >
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<TextBlock FontWeight="Bold" Text="{Binding ModelNumber}"></TextBlock>
<TextBlock FontWeight="Bold" Grid.Row="1" Text="{Binding ModelName}"></TextBlock>
</Grid>
</Border>
</DataTemplate>
</UserControl.Resources>
Here's how to use
<ListBox Name="lstProducts" x:Name="lstProducts" HorizontalAlignment="Center"
ItemTemplate="{StaticResource ProductDataTemplate}"></ListBox>
Data templates do not require databinding, in other words, you do not need to ItemsSource attributes to bind data to a ListBox, and you can call the ListBox.Items.Add () method yourself.