When overridden in a derived class, returns a DataTemplate based on custom logic.
Assembly: PresentationFramework (in PresentationFramework.dll)
public: virtual DataTemplate^ SelectTemplate( Object^ item, DependencyObject^ container )
- Type: System::Object
The data object for which to select the template.
- Type: System.Windows::DependencyObject
The data-bound object.
Typically, you use a template selector when you have more than one data template defined for the same type of objects. For example, if your binding source is list a list of student objects and you want to apply a particular template to the part-time students. You can do this by creating a class that inherits from DataTemplateSelector and overriding the method. Once your class is defined you can assign an instance of the class to the template selector property of your element.
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 method. In the following example, the 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.
We can then declare the TaskListDataTemplateSelector as a resource:
To use the template selector resource, assign it to the ItemTemplateSelector property of the ListBox. The ListBox calls the 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.
For the complete sample, see Introduction to Data Templating Sample.