Skip to main content

C# - How To Use A Datatemplate Selector In WPF [Beginner]


DataTemplates are an extremely powerful part of WPF, and by using them, you can abstract all sorts of display code. However, there are times when they fall short - and initially when I was learning WPF I was disappointed by that. For instance, you only get to set one DataTemplate on an items control, and while that made sense, it felt limiting. What if I wanted to use different templates depending on the content of the item? Do I have to build all that logic into a single data template?

And then I discovered DataTemplateSelectors! They are WPF's answer to the question I posed above - they let you write some logic that chooses what data template to use for an item. You could even, say, create an entirely new data template on the fly if you needed to. And it helps with one of WPF's main goals, separating out display (the DataTemplate itself) from logic (the DataTemplateSelector).

We are going to write a simple little application today, that is essentially just a list view containing a collection of strings. However, there is a twist - if the string is a path to an image on disk, instead of displaying the string, the list view will display the image. You can see a screenshot of it in action below:

App Screenshot

Time to dive into some code. First, lets write the two DataTemplates we need - one displaying the image, and one for displaying the string:
<DataTemplate x:Key="stringTemplate">
  <TextBlock Text="{Binding}"/>
</DataTemplate>

<DataTemplate x:Key="imageTemplate">
  <Image Source="{Binding Converter={StaticResource relToAbsPathConverter}}" 
         Stretch="UniformToFill" Width="200"/>
</DataTemplate>
 
Simple enough stuff. For when we just want to display the string, we use a TextBlock and bind the Text to the current item. When that string is an image path, however, we will be using an Image and binding the Source property to the string. The only quirk here is how the source property gets interpreted. If the path is relative, the Source property will think it is a reference to an internal program resource, and not a file on disk. So we have a converter that takes the relative path string and converts it to an absolute path string. You can learn more about binding converters from this tutorial .

Since I was just talking about the converter, might as well get the code for it out of the way:
public class RelativeToAbsolutePathConverter : IValueConverter
{
  public object Convert(object value, Type targetType,
      object parameter, CultureInfo culture)
  {
    String relative = value as string;
    if (relative == null)
      return null;
    return System.IO.Path.GetFullPath(relative);
  }

  public object ConvertBack(object value, Type targetType,
      object parameter, CultureInfo culture)
  {
    throw new NotImplementedException();
  }
}
 
All we do is cast the value to a string, and then use the handy GetFullPath method to get the full path for the given relative path. Since we don't need to use the ConvertBack method, I just have it set to throw a NotImplementedException.

Now that we have our Data Templates, lets write the DataTemplateSelector:
public class ImgStringTemplateSelector : DataTemplateSelector
{
  public DataTemplate ImageTemplate { get; set; }
  public DataTemplate StringTemplate { get; set; }

  public override DataTemplate SelectTemplate(object item, 
    DependencyObject container)
  {
    String path = (string)item;
    String ext = System.IO.Path.GetExtension(path);
    if (System.IO.File.Exists(path) && ext == ".jpg")
      return ImageTemplate;
    return StringTemplate;
  }
}
 
As you can see, to make your own DataTemplateSelector you create a class that extends the class DataTemplateSelector. This class has a single method that we need to override - SelectTemplate. This method will get called and get passed an item, and it needs to return what DataTemplate to use for that item. Here, we expect the item to be a string - and if the string represents a file path, and the file exists, and the extension is ".jpg", we return the template we are using for images, otherwise we return the template we are using for strings.

You are probably wondering, however, where the properties ImageTemplate and StringTemplate actually get set to the Data Templates we created earlier. Well, this happens in the xaml when we create an instance of the ImgStringTemplateSelector:
<local:ImgStringTemplateSelector 
    ImageTemplate="{StaticResource imageTemplate}" 
    StringTemplate="{StaticResource stringTemplate}" 
    x:Key="imgStringTemplateSelector" />
 
OK, now it is time to throw all of the xaml out there so that you can see how the ListView actually uses the ImgStringTemplateSelector we just created:
<Window x:Class="DataTemplateSelectorExample.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:DataTemplateSelectorExample"
    Title="Data Template Selector Example" 
    Height="300" Width="300" Name="This">
  <Window.Resources>
    <local:RelativeToAbsolutePathConverter x:Key="relToAbsPathConverter" />

    <DataTemplate x:Key="stringTemplate">
      <TextBlock Text="{Binding}"/>
    </DataTemplate>

    <DataTemplate x:Key="imageTemplate">
      <Image Source="{Binding Converter={StaticResource relToAbsPathConverter}}" 
             Stretch="UniformToFill" Width="200"/>
    </DataTemplate>

    <local:ImgStringTemplateSelector 
        ImageTemplate="{StaticResource imageTemplate}" 
        StringTemplate="{StaticResource stringTemplate}" 
        x:Key="imgStringTemplateSelector" />
  </Window.Resources>

  <Grid>
    <ListView ScrollViewer.CanContentScroll="False" 
              ItemsSource="{Binding ElementName=This, Path=PathCollection}" 
              ItemTemplateSelector="{StaticResource imgStringTemplateSelector}">
    </ListView>
  </Grid>
</Window>
 
The templates and the selector are all resources in the current window. This makes it so that when we get down to creating the ListView, we can set the ItemTemplateSelector to the static resource imgStringTemplateSelector. We also set the ItemsSource - we bind it to the PathCollection on the element This. What is the element This? Well, it happens to be the name of the window - you can see it up in the Nameproperty of the Window tag. And the PathCollection is a property on Window1:
public partial class Window1 : Window
{
  ObservableCollection<string> _PathCollection = new ObservableCollection<string>();

  public Window1()
  {
    _PathCollection.Add("Sunset.jpg");
    _PathCollection.Add("I'm not an image");
    _PathCollection.Add("Blue hills.jpg");
    _PathCollection.Add("Water lilies.jpg");
    _PathCollection.Add("More string action");
    _PathCollection.Add("Winter.jpg");

    InitializeComponent();
  }

  public ObservableCollection<string> PathCollection
  { get { return _PathCollection; } }
}
 
The only other thing of note is the fact that ScrollViewer.CanContentScroll is set to false on the ListView. This is just there to enable smooth scrolling on the list box - it doesn't try and scroll the items one at a time, it lets you scroll partially through an item. It is just a nicety because the ListView will contain images.

Well, that is it for this introduction to the DataTemplateSelector. You can grab the Visual Studio project for what we wrote today here.

Source Files:

Comments

Popular posts from this blog

C# Snippet - Shuffling a Dictionary [Beginner]

Randomizing something can be a daunting task, especially with all the algorithms out there. However, sometimes you just need to shuffle things up, in a simple, yet effective manner. Today we are going to take a quick look at an easy and simple way to randomize a dictionary, which is most likely something that you may be using in a complex application. The tricky thing about ordering dictionaries is that...well they are not ordered to begin with. Typically they are a chaotic collection of key/value pairs. There is no first element or last element, just elements. This is why it is a little tricky to randomize them. Before we get started, we need to build a quick dictionary. For this tutorial, we will be doing an extremely simple string/int dictionary, but rest assured the steps we take can be used for any kind of dictionary you can come up with, no matter what object types you use. Dictionary < String , int > origin = new Dictionary < string , int >();

C# Snippet - The Many Uses Of The Using Keyword [Beginner]

What is the first thing that pops into your mind when you think of the using keyword for C#? Probably those lines that always appear at the top of C# code files - the lines that import types from other namespaces into your code. But while that is the most common use of the using keyword, it is not the only one. Today we are going to take a look at the different uses of the using keyword and what they are useful for. The Using Directive There are two main categories of use for the using keyword - as a "Using Directive" and as a "Using Statement". The lines at the top of a C# file are directives, but that is not the only place they can go. They can also go inside of a namespace block, but they have to be before any other elements declared in the namespace (i.e., you can't add a using statement after a class declaration). Namespace Importing This is by far the most common use of the keyword - it is rare that you see a C# file that does not h

C# WPF Printing Part 2 - Pagination [Intermediate]

About two weeks ago, we had a tutorial here at SOTC on the basics of printing in WPF . It covered the standard stuff, like popping the print dialog, and what you needed to do to print visuals (both created in XAML and on the fly). But really, that's barely scratching the surface - any decent printing system in pretty much any application needs to be able to do a lot more than that. So today, we are going to take one more baby step forward into the world of printing - we are going to take a look at pagination. The main class that we will need to do pagination is the DocumentPaginator . I mentioned this class very briefly in the previous tutorial, but only in the context of the printing methods on PrintDialog , PrintVisual (which we focused on last time) and PrintDocument (which we will be focusing on today). This PrintDocument function takes a DocumentPaginator to print - and this is why we need to create one. Unfortunately, making a DocumentPaginator is not as easy as