DataTemplate in WPF

The WPF DataTemplate model provides you with great flexibility to define the presentation of your data. WPF controls have built-in functionality to support the customization of data presentation. A DataTemplate is the best feature to provide presentation/visual to your data in your way. A DataTemplate provides you a way to design your data visually better and you can apply your own creativity.

Simplest DataTemplate

A simple way to create a DataTemplate is to set the ItemTemplate property of the Control (a ListBox is used in this example) to a DataTemplate. Your DataTemplate is the the visual structure of your data object. The following DataTemplate is very simple. We are using a StackPanel and three items appear as three Label elements within the StackPanel. Each Label element is bound to a property of the Employee class.

DataTemplate in Resource

In most applications we define a DataTemplate either in a resource file or in a ResourceDictionary for reusability purposes.


Data Template With ItemsControl

An ItemsControl just has the collection of your items. Here you define only the ItemSource. But you can use the ItemsControl better with a DataTemplate. In the following example we are binding our ItemsControl with EmployeeList and we are using the Template property to specify a ControlTemplate to define the appearance of an ItemsControl. We are using the ItemsPanel property to specify an ItemsPanelTemplate that defines the panel that is used to hold the generated items and using the ItemTemplate to set a DataTemplate to define the visualization of the data objects. We are using the ItemContainerStyle property to specify the appearance of the element that contains the data.



I hope this article will help in understanding DataTemplates.