Dynamically Selecting DataTemplate For WPF ListView: Solution 1

Recently I had a chance to work on a project in which the requirement was to select various types of data templates based on the data. I encountered a bit difficulty, but afterwards I managed to get it work.

Let's have a look at the scenario first. Inside a WPF ListView, there are two GridViewColumns for storing Name and Age. Now the requirement is to highlight the name of the person based on certain age criteria. If the age is below 25, then the name should be highlighted as red else it should be in the green color, with the desired background. I know there are ways to implement this using the concept of triggers, but I personally refrain from using triggers for performance reasons.

So, what else ???

The option left was dynamically selecting data templates. In this article I will write about the simplest approach and later on I'll do the same thing using a Dictionary. Well, let's begin with our code.

First of all, I created a class named Employee and added some data that will be displayed on the UI. The code to perform this is:

class in WPF

The next thing I did is, defined the two DataTemplates in XAML as:

DataTemplate in XAML

Once the data templates are defined, the next task is to determine how to select the data templates dynamically. So to do this, Microsoft has provided the class DataTemplateSelector. Using this class, one can select the data templates based on the business requirements and here is the code:

WPF DataTemplateSelector

The next task is to bind this newly created class named MyTemplateSelector without XAML. So, in order to perform this task, I created a ResourceDictionary and kept both the data templates inside it as:

XAML ResourceDictionary

Until here we are almost done. The only thing pending is binding our ListView control to collection and setting the cell template, that can be done as:

WPF ListView control

Once everything is in place, we will get the desired output:

DataTemplate for WPF ListView

All the preceding can be done by inheriting from the MarkupExtension class also. I will cover that in my next article.

Up Next
    Ebook Download
    View all
    Learn
    View all