WPF Data Templates Tutorial and Samples

In this tutorial we will samples of how WPF Data Templates provides XAML way to create rich presentation of bound data and adds value to user experience and samples of it. Data template defines colour, layout and other aspects of data shown in WPF elements.

Data Template Example

<DataTemplate>

<Label Content=”{Binding Path=Name}” BorderBrush=”Black”

Background=”Green” BorderThickness=”1″ Foreground=”White” />

</DataTemplate>

You can set data template to Item Template of Listbox item to display name in different format specified above. Generally when you bind property or list to WPF control you only can bind single property. E.g. If you have customer object then you can either bind Name or Address or Email id to display.

WPF-Data-Template-Tutorial-Sample

WPF-Data-Template-Tutorial-Sample

Data Template removes this limitation where you can display as many properties you want and however you want. You can do this by adding container in Data Template which in turns hold many WPF elements which shows different properties.

Data template sample:

<DataTemplate>

<StackPanel>

<Label >

<Label.Content>

<WrapPanel HorizontalAlignment=”Stretch”>

<TextBlock>Company Name: </TextBlock>

<TextBlock Text=”{Binding CompanyName}” />

</WrapPanel>

</Label.Content>

</Label>

<Label Content=”{Binding Path=ContactName}” />

</StackPanel>

</DataTemplate>

If you apply this Data Template to any item template then you are showing to properties CompanyName and ContactName simultaneously.

You can set DataTemplate to ContentTemplate or ItemTemplate to change the appearance. For item controls you can either set DisplayMemberPath or ItemTemplate. DataTemplate can be defined in resources with key and can be used for multiple controls as a resource.

How to choose DataTemplate dynamically?

If you want to choose DataTemplate for you control dynamically WPF provides you with Abstract Class DataTemplateSelector which you have to extend and override it’s SelectTemplate method in which you will define logic to return DataTemplate object based on business logic. You can add this selector in the resource and set it to ContentTemplateSelector. Whenever an item will get added automatically SelectTemplate method will get called and DataTemplate will be set for that item.

DataTemplate for hierarchical data:

HierarchicalDataTemplate is class which provide way to define DataTemplate for hierarchical data controls like TreeView or menu. This class gives ItemSource and ItemTemplate properties which are for subitems. If hierarchy is of more than one level then you can set ItemTemplate to another HierarchicalDataTemplate. It also provides ItemTemplateSelector property if you want it to set dynamically.

Leave a Reply

Your email address will not be published. Required fields are marked *