Data Template Selector in Windows 8 Metro XAML App

It has been work around to have more than one data template in a list to display the data. In Windows 8 it has been eased, WinRT introduces the DataTemplateSelector class, where we could have more than one template to display in an items source control in Windows 8. In this article we would discover that.

To explore the sample, you definitely need Windows 8 Consumer Preview and Visual Studio 2012 RC.

As you see below, I have created a Windows Metro Style Blank App in XAML.

We’ll create a class which would inherit from the class DataTemplateSelector, which requires “Windows.UI.Xaml.Controls” to be referenced.

Now we would add the number of properties of type DataTemplate, which requires “Windows.UI.Xaml” to be referenced.

As you see above, we have three properties of type DataTemplate, such as PictureTemplate, VideoTemplate, StoryTemplate.

We would have the SelectTemplateCore method overridden, and there we would define the logic for selecting the template based on. As you see in the below image, the type is checked to provide the template. You could have your own logic based on your own requirement.

Now we would add three templates, as StandardStyles is a Resource Dictionary provided by the template, we would use it for storing our DataTemplates.

Design Note: While designing DataTemplates for a DataTemplateSelector, keep in mind that the DataTemplate should have same Height and Width, of the parent container (Grid, StackPanel, Border, etc…), if you are providing Margin or padding for it, should be the same for all.

The following Template describes a DataTemplate for a Video Data.

The following Template describes a DataTemplate for an Image Data.

The following Template describes a DataTemplate for a Story Data.

Now we have to add reference of the namespace where the TemplateSelector is located, in our case we have created in Common, so be it.

We would add the DataTemplateSelector in the resources.

And we would use it, as follows: it has to be a StaticResource to ItemTemplateSelector property.

Assuming we have sample data (Dig into code, to find out about the sample data), we are running the application.

And we have successfully displayed a list with multiple DataTemplates.

Hope this article helps, thanks for reading.

Source Code: Click Here

Article as PDF: Click Here

Related Posts:

1) FileSavePicker in Windows 8 XAML App

2) FileOpenPicker in Windows 8 XAML App

3) Save as Image in Picture Library in Windows 8 XAML Metro App

4) Remove Windows 8 from your Dual-Boot Setup