WPF Tutorial - How To Use A DataTemplateSelector
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:
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 here, in a tutorial that The Reddest wrote just the other day.
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 Name
property 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. And, as always, leave any questions or comments below.