datatemplateselector winrt

Having used DataTemplateSelectors previously with WPF and similar on Silverlight/Windows Phone I decided to check out whether they work the same in a xaml Metro application. It turns out to be pretty much the same (barring a few things being a bit buggy in the Win8 Developer Preview). Anyway, for reference, here’s a description:

First I created a custom data template selector. This enables you to intercept the decision of which template to use.

If you’re used to other xaml technologies you need to be careful with your namespace declaration as the syntax has changed for WinRT:

Using declaration

xmlns:FlipView="using:FlipView"

One thing we haven’t done is to create and set up the DataTemplates:

DataTemplates

<UserControl.Resources>

<DataTemplate x:Key="myPersonTemplate">

<Border Background="CornflowerBlue">

<TextBlock Text="{Binding Name}"

FontSize="64"

Foreground="Red"

HorizontalAlignment="Center"

VerticalAlignment="Center" />

</Border>

</DataTemplate>

<DataTemplate x:Key="myPlaceTemplate">

<Border Background="Orange">

<Grid>

<Image Source="{Binding Image}"></Image>

<TextBlock Text="{Binding PlaceName}"

FontSize="128"

Foreground="AliceBlue"

HorizontalAlignment="Center"

VerticalAlignment="Center" />

</Grid>

</Border>

</DataTemplate>

<FlipView:MyDataTemplateSelector x:Key="mySelector"

PersonTemplate="{StaticResource myPersonTemplate}"

PlaceTemplate="{StaticResource myPlaceTemplate}">

</FlipView:MyDataTemplateSelector>

</UserControl.Resources>

Note that I have created the DataTemplates with a key in the UserControl Resources. This allows me to access the item as a StaticResource; I do this to set the properties on my custom DataTemplateSelector. Now the above may be used with any ItemsControl since that defines an ItemTemplateSelector property on which we can set our custom DataTemplateSelector. It just remains to mock up some data and try it out on a few different Containers: