Igor Kulman

Using different data templates with GridView in Windows 8 apps

· Igor Kulman

GridView and ListView are the two of the most commonly used components in Windows 8 apps. Items in these two components are displayed according to the DataTemplate give as the ItemTemplate property. If you do not want to display all the items the same way, you need to use a custom ItemTemplateSelector.

Using ItemTemplateSelector in Windows 8 apps is easier and more straightforward that in Windows Phone 7 (I wrote about that here in Slovak). All you need to do is to create a class inheriting from the DataTemplateSelector and set the ItemTemplateSelector property of GridView (or ListView) to this new class.

When inheriting from the DataTemplateSelector you need to override the SelectTemplateCore method. In this method you have accees to the binded item and and you can use it to decide which DataTemplate to return. You can define your DataTemplates in the App.xaml and access them via the Application.Current.Resources array with casting, but that is a bad habbit. A better solution would be to define public DataTemplate properties in your class and assign them in XAML.

A custom DataTemplateSelector class may look like this

public class MainGridTemplateSelector : DataTemplateSelector
        public DataTemplate MagazineTemplate { get; set; }
        public DataTemplate BigMagazineTemplate { get; set; }

        protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
            return (item is MagazineViewModel).IsTop ? BigMagazineTemplate : MagazineTemplate;

This class chooses one of two DataTemplates (MagazineTemplate, BigMagazineTemplate) according to the item’s IsTop boolean property.

In your XAML, first declare the MainGridTemplateSelector and set the DataTemplate properties class

<common:MainGridTemplateSelector x:Key="MainGridTemplateSelector"
    MagazineTemplate="{StaticResource MagazineTemplate}"
    BigMagazineTemplate="{StaticResource BigMagazineTemplate}" />

Where MagazineTemplate and BigMagazineTemplate are DataTemplates defined in your XAML. Then simply set the ItemTemplateSelector property of the GridView (ListView)

     ItemTemplateSelector="{StaticResource MainGridTemplateSelector}"

See also