DataTemplate: What is it?
A DataTemplate provides the Visual representation of a single data item (a data object).
DataTemplates are mostly used in the context of ItemsControl and ContentControl (and their derived classes) to determine how data items need to be displayed.
The following is an example of using a DataTemplate:
If we need to display a list of dates, we could use a ListBox (ItemsControl) and set its Items property to a list of DateTime objects.
The ListBox would display each date according to their default representation (text string). However, for our particular needs, we want each date to be represented by three different TextBlock controls, each with a different background, stacked one on top of the other vertically. This can be done by setting the ItemTemplate (of type DataTemplate) of the ListBox to a custom DataTemplate.
<DataTemplate DataType="{x:Type s:DateTime}">
<StackPanel>
<TextBlock Text="{Binding Path=Year}" Background="Red" />
<TextBlock Text="{Binding Path=Month}" Background="Blue" />
<TextBlock Text="{Binding Path=Day}" Background="Green" />
</StackPanel>
</DataTemplate>
No comments:
Post a Comment