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. DataTemplate is the best feature to give presentation/visual to your data in your way. DataTemplate provide you the way that you can design your data visually better and you can apply your own creativity.

Simplest DataTemplate

Simple way to create DataTemplate is to set the ItemTemplate property of the Control(ListBox 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 having stackpanel and three items appears as three Label elements within a StackPanel. Each Label element is bound to a property of the Employee class.


DataTemplate in Resource

In Most of the application we define DataTemplate in Resource file or either in ResourceDictionary for reusability purpose.



Data Template With ItemsControl

ItemsControl is just having collection of your items here you define only the ItemSource. But you can use itemsControl better with DataTemplate. In the below 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.



Hope this article will help in understanding DataTemplate.

Ebook Download
View all
Learn
View all