I have a listbox populated by items. Each item contains an object as follow:
public Contact(int idContact, string pseudo, string prenom, string nom, string numero, bool isOuter)
{
this.IdContact = idContact;
this.Pseudo = pseudo;
this.Prenom = prenom;
this.Nom = nom;
this.NumerosTel = numero;
this.IsOuter = isOuter;
}
Now I would like to apply a different style to these items according to the IsOuter value as it's a boolean value. I've heard about DataTemplateSelector but cannot really figure out how it really works.... Does somebody can show me how to do it ?
First, you create a DataTemplateSelector
like this:
public class MyTemplateSelector : DataTemplateSelector {
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container) {
var contact = (Contact)item;
if (contact.IsOuter == true) {
return (DataTemplate)Application.Current.Resources["DataTemplate1Name"];
} else {
return (DataTemplate)Application.Current.Resources["DataTemplate2Name"];
}
}
}
In this code, the DataTemplates should be in App.xaml. Basically, the method must return the DataTemplate that you want as a DataTemplate object. How will you get that object is entirely up to you.
Second, you need to set the ItemTemplateSelector
of the ListBox
like this:
listbox.ItemTemplateSelector = new MyTemplateSelector();
And that's it. Now different items will have different templates, based on the IsOuter property.
Some thoughts
You may want to have some more reusable template selectors. For example, you may have an interface with one DataTemplate
property and in the SelectTemplateCore
, check if the item implements the interface and if yes - return the value of that property.
Anyway, the code above should work for now, and if you need more DataTemplateSelector
s in the future, you'll figure out the most convenient way for you to write/use them. :)