DataContext, Data Templates and Data Template Selectors

I spent some time today working on DataTemplateSelectors. I’d never used them before, but it made me think about all the different ways there are to set the DataContext in WPF. After talking through this with a friend, I realized that maybe some of these minor nuances aren’t very clear. I figured if I write about it, at least I can reference it again later when I forget.

OK, my first assumption here is that you’re being a good programmer and using MVVM, this is WPF after all.

Binding To Code-Behind

This is the most basic kind of binding. When you first learn MVVM, this is probably going to be your first step. Binding to code-behind just requires you to set your DataContext to the xaml.cs file attached to your View –

<Window .....
        DataContext="{Binding RelativeSource={RelativeSource Self}}">           
</Window>

In the long run I don’t recommend this one, you’re always going to want to bind a View to a ViewModel in a separate class. It just makes it so much cleaner. This leads to my next header

Binding To ViewModel

This one is really similar to binding to your code behind. The only difference here is that instead of binding to yourself, you’re binding to your View Model. Simple right, OK, here’s the code –

<Window x:Class="MyProgram.MainWindow"
        xmlns:local="clr-namespace:MyProgram"
        mc:Ignorable="d">

    <Window.DataContext>
        <local:MainWindowViewModel />
    </Window.DataContext>
</Window>

Make sure to get the correct namespace (in this case local) of your View Model. When using this style of datacontext setting, you’re going to have to do this for each and every View. At first this might seem OK, but the further into this you get, the more cumbersome this method becomes.

OK, onto the next method; DataTemplates!

Binding Using DataTemplates

DataTemplates are used all over WPF (seriously, you should take a look into how awesome data templating is in ListViews if you don’t believe me). When it comes to Views and View Models the data template allows you to load your Views by specifying the View Model you want. Instead of loading View first, you can call the View Model (along with it’s constructor) and the ContentPresenter will figure out what View to serve up alongside it.

The beauty of this is you can now pass around data between your view models, making it easier to structure your program.

You still need to set the DataContext of your initial entry point View. In the case above it’s the MainWindow and MainWindowViewModel. So, even in this method, make sure to set the DataContext first.

Now, add some kind of presenter (it can be a ContentPresenter, ContentControl or UserControl). This will be the View Controller that will change out the different views according to your bindings. Here’s the code for the View –

<Window x:Class="MyProgram.MainWindow"
        xmlns:local="clr-namespace:MyProgram"
        mc:Ignorable="d">

    <Window.DataContext>
        <local:MainWindowViewModel />
    </Window.DataContext>

    <Grid>
        <ContentPresenter Content="{Binding View}" />
    </Grid>
</Window>

Here’s the code for your View Model (I’m not including the INotifyPropertyChanged interface, I’m assuming you’ve got that figured out by now, but if you’re looking for a framework, try JustMVVM). MVVMBase is just a base class that all View Models must inherit from.

class MainWindowViewModel : MVVMBase
{
    private MVVMBase _currentViewModel;
    public MVVMBase CurrentViewModel
    {
        get { return _currentViewModel; }
        set
        {
                _currentViewModel = value;
                OnPropertyChanged();
        }
    }

    public MainWindowViewModel()
    {
        // Setting View to Home screen
        CurrentViewModel = new HomeViewModel();
    }
}

For the application to figure out what view to load for the ContentPresenter, we need to add a Data Template. The simplest place to put this is in App.xaml, then it’ll work throughout the entire application, but in reality you can put this in any Resources section

Below are 3 different data templates for 3 different views.

<Application x:Class="MyProgram.App"
             xmlns:view="clr-namespace:MyProgram.View"
             xmlns:viewmodel="clr-namespace:MyProgram.ViewModel"
             Startup="Application_Startup"
             StartupUri="MainWindow.xaml">

    <Application.Resources>

        <DataTemplate DataType="{x:Type viewmodel:HomeViewModel}">
            <view:Home />
        </DataTemplate>

        <DataTemplate DataType="{x:Type viewmodel:SettingsViewModel}">
            <view:Settings />
        </DataTemplate>

        <DataTemplate DataType="{x:Type viewmodel:HelpViewModel}">
            <view:Help />
        </DataTemplate>

    </Application.Resources>
</Application>

For most of my applications that I’ve worked on, this has worked out great. I have a single spot where I put all my data templates and then I’m in complete control over what views are being loaded. There are occasional situations that require an even more complicated solution, so here we go, my final option, the DataTemplateSelector.

Data Template Selector

In theory this is another alternative to using Data Templates, but it gives a little more control over the issue. Sometimes a need arises where you have multiple Views for a single View Model, or you’ve created a generic form of ViewModel<T> but you can’t define a DataTemplate for generics in XAML. In this case, you can create a Data Template Selector, which allows you to select the associated View template in code.

Here’s some example code of the Selector –

public class CustomDataTemplateSelector : DataTemplateSelector
{
    public DataTemplate HomeTemplate { get; set; }
    public DataTemplate SettingsTemplate { get; set; }
    public DataTemplate HelpTemplate { get; set; }

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        if (item == null)
            return base.SelectTemplate(item, container);

        var viewModel = item as PropertyChangedBase;
        var viewModelType = viewModel.GetType();

        if (viewModelType.IsGenericType && viewModelType.GetGenericTypeDefinition() == typeof(HomeViewModel<>))
                return HomeTemplate;

        else if (viewModelType == typeof(SettingsViewModel))
            return SettingsTemplate;

        else if (viewModelType == typeof(HelpViewModel))
            return HelpTemplate;

        else
            return base.SelectTemplate(item, container);
    }
}

Let’s unpack this a little bit. The properties at the top can be set in the XAML to the data templates we created in the previous section (see below for how it’s done). The first part of the if statement shows how you can handle a generic type for a template selector. This means that any HomeViewModel<T> will load the HomeTemplate.

The reason I ended up using this over Data Templates is for the else part at the end. I was creating a library that was to be consumed by others. I wanted to be very specific about what templates were loaded in my library, but also leave open the possibility of other people adding their own templates. I guess I could have created some extensible class that allows people to add more templates, but by calling the base implementation of the DataTemplateSelector

return base.SelectTemplate(item, container);

I don’t have to do anything special, I just let the normal DataTemplates take over again like usual.

Here’s how this Selector was implemented in XAML –

<Grid>
    <Grid.Resources>

        <DataTemplate x:Name="HomeTemplate" >
            <view:Home />
        </DataTemplate>

        <DataTemplate x:Name="SettingsTemplate" >
            <view:Settings />
        </DataTemplate>

        <DataTemplate x:Name="HelpTemplate" >
            <view:Help />
        </DataTemplate>

        <viewmodel:CustomDataTemplateSelector x:Key="ViewTemplateSelector"
                                              HomeTemplate="{StaticResource dialogException}"
                                              SettingsTemplate="{StaticResource dialogOKCancel}"
                                              HelpTemplate="{StaticResource dialogOK}" />

    </Grid.Resources>

    <!--  Dialog User Control  -->
    <ContentPresenter Content="{Binding View}"
                      ContentTemplateSelector="{StaticResource ViewTemplateSelector}" />
</Grid>

And like I said, any other View / View Model templates can either be added to the Template Selector (if you have access to it) or can just be placed in App.xaml like usual.

Well, I think that’s all I’ve got about Data Templates. Hopefully by putting this all together in one place I’ve made somebody’s life easier. If you see anything wrong, let me know in the comments.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s