Saturday, January 4, 2014

DataTemplating Overview

DataTemplate is a very powerful concept which allows you to provide a visualization for your objects in your application. DataTemplate objects are very useful specially dealing with collections. If you bind your collection with any of the ItemsControl, say ListBox then by using a DateTemplate one can change the appearance of data objects very easily. Well, now let's create a DataTemplate quickly.

Let's start by creating a class called Employee:

FirstName and Age will be our business objects that will reside in our application. Now we will go ahead and show the value of these objects on screen in a WPF application. For that our XAML will look like:

Now looking at the code-behind:

In code-behind, we have set the values for FirstName and Age with DataContext of main window. So, that XAML can bind to these values via EmployeeDetail property. At this point of time, if you will run the application, you will see:

By above image you can see that the default implementation of DataTemplate in WPF has simply put the string on my window, where TemplatingOverview is my namespace. So, to make it work in order to show proper values, let's go ahead and override ToString on Employee object, something like this:

In above snippet we are saying that please provide us the string with given format. Now, if you will go ahead and run this again you will find that our DataTemplate is changed and now it is using our overriden ToString.

Till here, I showed that what will happen if you will not provide your own DataTemplate. Now instead of writing overriden method, same thing can be performed fully in XAML as:

In above snippet, we have created a DataTemplate on the ContentControl and inside this DataTemplate, one can do any styling and can create any number of visual elements. Later on, these visual elements can be bind to any public property of Employee object. Please note, the Datacontext for this DataTemplate will be EmployeeDetail. Now, if you will run the app, still you can see the value of Employee object.

Sharing DataTemplate
Now in order to share this DataTemplate between multiple ContentControls, one has to make this as a part of resource. Let's have a look at the complete code to get clear idea:

Hope you enjoyed reading. In Next article, I'll be writing about DataTemplateSelector.

No comments:

Post a Comment