Wednesday, January 22, 2014

Dynamically selecting DataTemplate for WPF ListView - Way 2

In continuation to my previous article titled 'Dynamically selecting DataTemplate for WPF ListView', in this article, I am discussing about the alternative way to achieve the same goal. But here, to make the example simple, I am going to display only Employee names as shown below:













Now this to achieve this, I am going to inherit MarkupExtension class provided by Microsoft. This class will give me the DataTemplate. If you will explore further, you will came to know that this MarkupExtension class has only one method named as ProvideValue, which will return me the appropriate template based on the supplied value. 

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








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















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














And last but not the least, our XAML:















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

No comments:

Post a Comment