Windows 8 App – Using DataTemplateSelector to Select FlipView Template

Jared Johnson, 13 May 2013

While working on a Windows 8 Xaml and C# app, I was using a FlipView control to display data, however I wanted the layout of each item to change with the data displayed. To achieve this I used the DataTemplateSelector class which will switch between predefined templates.

Windows 8 App Using DataTemplateSelector to Select FlipView Template

To use the DataTemplateSelector you must create your own class which inherits from DataTemplateSelector. This class must then have properties of the type DataTemplate for each of the templates that will be switched between. 

Windows 8 App Using DataTemplateSelector to Select FlipView Template

Next the method SelectTemplateCore must be overridden, here the logic for selecting the correct template is contained, the method must return the template that will be used for the FlipView control, you can use your own logic for selecting which template. 

Windows 8 App Using DataTemplateSelector to Select FlipView Template

These templates should be defined in the StandardStyles.xaml. In the xaml of the page where our FlipView is contained we must add a reference to our custom TemplateSelector class. Then add in the resources the TemplateSelector, passing into its properties the names of the templates that were defined in StandardStyles.xaml. 

Windows 8 App Using DataTemplateSelector to Select FlipView Template

Now to use the TemplateSelector on the FlipView it is added as a StaticResource to the FlipViews ItemTemplateSelector property. 

Windows 8 App Using DataTemplateSelector to Select FlipView Template

Now depending on the items in the FlipView it will switch between templates, the DataTemplateSelector can also be used on other Xaml controls such as the GridView.