In this example, the binding source is a list of Task objects. One of the properties of a Task object is Priority. There are two data templates defined, myTaskTemplate and importantTaskTemplate.
To supply logic to choose which DataTemplate to use based on the Priority value of the data object, create a subclass of DataTemplateSelector and override the SelectTemplate method. In the following example, the SelectTemplate method provides logic to return the appropriate template based on the value of the Priority property. The template to return is found in the resources of the enveloping Window element.
using System.Windows;
using System.Windows.Controls;
namespace SDKSample
{
public class TaskListDataTemplateSelector : DataTemplateSelector
{
public override DataTemplate
SelectTemplate(object item, DependencyObject container)
{
if (item != null && item is Task)
{
Task taskitem = item as Task;
Window window = Application.Current.MainWindow;
if (taskitem.Priority == 1)
return
window.FindResource("importantTaskTemplate") as DataTemplate;
else
return
window.FindResource("myTaskTemplate") as DataTemplate;
}
return null;
}
}
}
We can then declare the TaskListDataTemplateSelector as a resource:
<Window.Resources>
...
<local:TaskListDataTemplateSelector x:Key="myDataTemplateSelector"/>
...
</Window.Resources>
To use the template selector resource, assign it to the ItemTemplateSelector property of the ListBox. The ListBox calls the SelectTemplate method of the TaskListDataTemplateSelector for each of the items in the underlying collection. The call passes the data object as the item parameter. The DataTemplate that is returned by the method is then applied to that data object.
<ListBox Width="400" Margin="10"
ItemsSource="{Binding Source={StaticResource myTodoList}}"
ItemTemplateSelector="{StaticResource myDataTemplateSelector}"
HorizontalContentAlignment="Stretch"/>
For the complete sample, see Introduction to Data Templating Sample.