OpenLightGroup Blog


Blogs from

Type Based Template Selector for WinRT

I missed the implicit DataTemplates of Silverlight so much in WinRT, that I had to create a reusable template selector to help provide a similar behavior.

First let’s look at the DataTemplateSelector I came up with:

public class TypeBasedDataTemplateSelector : DataTemplateSelector
    public TypeBasedDataTemplateSelector()
        this.TemplateSuffix = "DataTemplate";
    public string TemplateSuffix { get; set; }
    public DataTemplate DefaultTemplate { get; set; }
    protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
        DataTemplate template = this.DefaultTemplate;
        if (item != null)
            var templateName = item.GetType().Name + this.TemplateSuffix;
            if (Application.Current.Resources.ContainsKey(templateName))
                template = Application.Current.Resources[templateName] as DataTemplate;
        if (template == null)
            template = base.SelectTemplateCore(item, container);
        return template;

This DataTemplateSelector allows you to specify a DefaultTemplate to use in case it cannot locate a template for the type of item it is bound to. It also provides a TemplateSuffix that allows for multiple templates to be defined for a single type. For example, you could have the NewsItemDataTemplate and the NewsItemListItemTemplate defined in your application.

This is what it looks like to use the template selector in XAML:

First we defined the selector as a resource:

<converters:TypeBasedDataTemplateSelector x:Key="NewsItemTemplateSelector"
    DefaultTemplate="{StaticResource DefaultNewsItemDataTemplate}"
    TemplateSuffix="ContentTemplate" />

Then we wire it up to our control:

<ContentControl Content="{Binding}"
    ContentTemplateSelector="{StaticResource NewsItemContentTemplateSelector}" />

Now when the content of the control changes our TemplateSelector  will find a template in the Application Resources that matches our type and TemplateSuffix. This allows you to have a TwitterNewsItem and an RssNewsItem that use different templates when bound to a control using the selector.

Happy coding!

Comments are closed.