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;


<DataTemplate x:Key=”dtCustomer”>
<TextBlock Text=”{Binding Name}” FontSize=”25″/>
<DataTemplate x:Key=”dtPrefCustomer”>
<TextBlock Foreground=”Green” Text=”{Binding Name}” FontSize=”25″ FontWeight=”Bold”/>
<local:CustomerDataTemplateSelector x:Key=”cdst” CustTemplate=”{StaticResource dtCustomer}” PrefCustTemplate=”{StaticResource dtPrefCustomer}”/>
<Grid Background=”{StaticResource ApplicationPageBackgroundBrush}”>

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


Here is the result.


3 thoughts on “Using DataTemplateSelector in Metro Style App

  1. Pingback:
  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 Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s