James Montemagno
James Montemagno

Live, Love, Bike, and Code.

Tags


Twitter


Fun with Windows 8 DataItemTemplates

James MontemagnoJames Montemagno

So you are probably using GridViews and ListViews all over the place. In some instances you will most likely even have a situation where you you have a DataSource with a few DataGroups. Each DataGroup might actually be all different or it might even have different items in its list. If you have a nice base class such as StandardDataItem then this will work just fine. So here is where the fun comes in because usually each DataItem is going to have a different DataTemplate.

This is where DataItemTemplates come in.

So first we will pretender I have a few items such as:

  1. MovieItem
  2. RecordedTVItem

I want to show the latest 5 or 6 from each category on my home screen of my app.

So the first thing you will want to do is construct up a DataSource:

var group1 = new StandardDataGroup("recent_movies", "Recent Movies", "Recent Movies", string.Empty, string.Empty, 0, movies);

var group2 = new StandardDataGroup("recent_recordings", "Recent Recordings", "Recent Recordings", string.Empty, string.Empty, 0, recordings);


DataSource.AllGroups.Add(group1);
DataSource.AllGroups.Add(group2);

If you don’t have/know about StandardDataGroup you can start up any new Window Store App sample and find them. They are a good basis for you to start.

Alright next up I am going to assume that you already created ItemTemplates for each. We will assume

  1. MovieItemTemplate
  2. RecordedTVItemTemplate

So now we will create a new class called “MainItemTemplateSelector.cs”

Now the key here is to derive from “DataTemplateSelector”

public class MainItemTemplateSelector : DataTemplateSelector
{
}

All you have to do is override 1 method here:

protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
    var movie = item as MovieDataItem;

    if (movie != null)
    {
        return Application.Current.Resources["MovieItemTemplate"] as DataTemplate;
    }

    var recorded = item as RecordedTVDataItem;

    if (recorded != null)
    {
        return Application.Current.Resources["RecordedTVItemTemplate"] as DataTemplate;
    }

    return null; //probably throw exception as this would be bad
}

Alright and now for the fun stuff in your XAML

First in the .Resources you will want to specify:

 common:MainItemTemplateSelector x:Key="MainItemTemplateSelector"

Then you will want to specify the ItemTemplateSelector in your grid view or itemsview:

<GridView ItemsSource="{Binding Source={StaticResource groupedItemsViewSource}}" ItemTemplateSelector="{StaticResource MainItemTemplateSelector}" 

Boom you are good to go!

Now you will want to do some custom work on the back end when you click one of these. you will have to do something similar as well for the item that is selected so you can navigate to the correct page.

Live, Love, Bike, and Code

Comments