Implementing a custom DataTemplateSelector in WinRT

In one of the projects that I am currently working on I needed to implement this. I needed this because I am using the ItemsControlto display a list of Items. The problem that I had is that I have several type of objects in my list, and I wanted to use a different template for each of them.

1. Markup for a standard ItemsControl

- Define the DataTemplate as a static resource:

<Page.Resources>
    <DataTemplate x:Key="TempA">
        <Border Background="Red">
            <TextBlock Text="{Binding Title}" />
        </Border>
    </DataTemplate>
</Page.Resources>

- Declare your Items Control to use the Data Template:

<ItemsControl x:Name="items"
             ItemsSource="{Binding Items}"
             ItemsTemplate="{StaticResource TempA}" />

2. Implement a DataTemplateSelector to use several Templates in an ItemsControl

- Implement the selector to use a different template based in the object type:

public class ItemsTemplateSelector : DataTemplateSelector
{
    public DataTemplate TemplateA { get; set; }
    public DataTemplate TemplateB { get; set; }
 
    protected override DataTemplate SelectTemplateCore
        (object item, DependencyObject container)
    {
        if (item is ObjectTypeA)
        {
            return TemplateA;
        }
        else if (item is ObjectTypeB)
        {
            return TemplateB;
        }
        else
        {
            return base.SelectTemplate(item, container);
        }
    }
}

- Declare your DataTemplates in Resources

<Page.Resources>
    <DataTemplate x:Key="TempA">
        <Border Background="Red">
            <TextBlock Text="{Binding Title}" />
        </Border>
    </DataTemplate>
    <DataTemplate x:Key="TempB">
        <Border Background="Blue">
            <TextBlock Text="{Binding Title}" />
        </Border>
    </DataTemplate>
</Page.Resources>

- Declare your DataTemplateSelector in Resources

<views:ItemsTemplateSelector x:Key="itemsTemplateSelector"
                            TemplateA="{StaticResource TempA}"
                            TemplateB="{StaticResource TempB}" />

- Update the ItemsControl to use your DataTemplateSelector

<ItemsControl x:Name="items"
             ItemsSource="{Binding Items}"
             ItemTemplateSelector="{StaticResource itemsTemplateSelector}" />
Pedro Alonso

About The Author

Pedro Alonso is a freelance Software Engineer with international experience and back end development specialization. Working on a wide range of projects over the last 5 years has allowed him to develop his knowledge of C#, .NET Framework, SQL Server, applications architecture and design patterns among other things. He is also a passionate traveler and photography lover.

1 Comment

  1. [...] Implementing a custom DataTemplateSelector in WinRT. Tu voto:Compartir:TwitterLinkedInMe gusta:Me gustaSe el primero en decir que te [...]