How to use DataTemplateSelector with Windows 8.1 Store AppsThis article will cover how to implement DataTemplateSelector to have more versatile control of our XAML and our code behind. We will be separating our DataTemplates into our App.xaml and every single decision will be handled by our TemplateSelector class. Lets begin by adding our example classes for this project. Go ahead and add our classes as:
Now, next step is to add our Main class which will be holding the main page data.
Please make sure that you have ObservableDictionary class added to your project!! Lets add a new page and call it MainPage. Change the code for the project to look like:
It can be seen that we have created two lists (firstItem, secondItem) holding the data and added these items to our PageItems list. Reason is that, we will be having a CollectionViewSource on our page which "Groups" will be binded to. Our TemplateSelector will iterate through these objects. Lets move on and add our DataTemplateSelector class under your Common folder (or wherever you would like to hold the data).
Now, we can see that we have two DataTemplate properties. That means we will be returning either one of them depending on the result for overwritten SelectTemplateCore method.
OK. Now we need our templates ready. Selector will be making the decision, but we need to bind our DataTemplates to their xaml. Go ahead and append your App.xaml to include:
So we can say that FirstItemDataTemplate will bind to FirstItemTemplate and SecondItemDataTemplate will bind to SecondItemTemplate. Lets move on and change our MainPage.xaml as
We have our DataContext referenced on the page as DefaultViewModel so we can bind Groups to our CollectionViewSource. And our ItemsTemplateSelector will decide the DataTemplate for our GridView. Go ahead and run your application. Results should look like:
If you have any questions, feel free to ask me.
Enjoy Coding:) comments powered by Disqus