Using DataTemplateSelector in Metro Style App

This is a short post on using DataTemplateSelector to show items differently in the same list.

Lets say we have

public class Customer
{
public string Id { get; set; }
public string Name { get; set; }
}

public class PreferredCustomer: Customer
{
public int Discount { get; set; }
}

and we create a list of customers like this and set the itemssource to any ItemsControl

List<customers> = new List();
customers.Add(new Customer { Id = “1”, Name = “customer..1” });
customers.Add(new PreferredCustomer { Id = “2”, Name = “customer..2”, Discount=10 });
customers.Add(new Customer { Id = “3”, Name = “customer..3” });
customers.Add(new PreferredCustomer { Id = “4”, Name = “customer..4”, Discount=20 });
customers.Add(new Customer { Id = “5”, Name = “customer..5″ });

list1.ItemsSource = customers;

In resources section, we create couple of datatemplates and a DataTemplateSelector which returns a datatemplate based on the item.

We bind the ItemTemplateSelector property of Listview to the one we created in resource section.

public class CustomerDataTemplateSelector : DataTemplateSelector
{
public DataTemplate CustTemplate { get; set; }
public DataTemplate PrefCustTemplate { get; set; }

protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
Customer c = (Customer)item;
DataTemplate dt = c is PreferredCustomer ? this.PrefCustTemplate : this.CustTemplate;
return dt;
}

}

<Page
x:Class=”Application1.BlankPage1″
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;
xmlns:local=”using:Application1″
xmlns:d=”http://schemas.microsoft.com/expression/blend/2008&#8243;
xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006&#8243;
mc:Ignorable=”d”>
<Page.Resources>
<DataTemplate x:Key=”dtCustomer”>
<TextBlock Text=”{Binding Name}” FontSize=”25″/>
</DataTemplate>
<DataTemplate x:Key=”dtPrefCustomer”>
<TextBlock Foreground=”Green” Text=”{Binding Name}” FontSize=”25″ FontWeight=”Bold”/>
</DataTemplate>
<local:CustomerDataTemplateSelector x:Key=”cdst” CustTemplate=”{StaticResource dtCustomer}” PrefCustTemplate=”{StaticResource dtPrefCustomer}”/>
</Page.Resources>
<Grid Background=”{StaticResource ApplicationPageBackgroundBrush}”>

<ListView Width=”300″ x:Name=”list1″ FontSize=”30″ ItemTemplateSelector=”{StaticResource cdst}”/>

</Grid>
</Page>

Here is the result.

3 thoughts on “Using DataTemplateSelector in Metro Style App

  1. Pingback: WindowsDevNews.com
  2. Works well when adding items dynamically, thanks. But how do you respond to changes, for example if you were to change a preferred customer to a normal one?

Leave a comment