Dynamically Selecting DataTemplate For WPF ListView: Solution 2

In continuation of my previous article titled "Dynamically Selecting DataTemplate for WPF ListView", in this article, I am discussing an alternative way to do the same thing. But here, to make the example simple, I will display only Employee names as shown below:

Now to do this, I will inherit from the MarkupExtension class provided by Microsoft. This class will provide the DataTemplate. If you explore further, you will learn that this MarkupExtension class has only one method named ProvideValue that will return the appropriate template based on the supplied value.

Before inheriting MarkupExtension, I created a class named MyDataTemplateDictionary, that will inherit Dictionary<object, DataTemplate>. Please note, here the key will be my DataTemplate name and value will be the DataTemplate. The following is the code depicting that:

Next is the class inheriting MarkupExtension. Since there is nothing much to explain in this code, I'm directly showing it:

And finally the class inheriting DataTemplateSelector, that is exactly the same code as shown in previous article:

And last but not the least, our XAML:

And we are done. Isn't it the cleaner approach?

Up Next
    Ebook Download
    View all
    View all