DataTemplate.DataType Property
Gets or sets the type for which this DataTemplate is intended.
Namespace: System.Windows
Assembly: System.Windows (in System.Windows.dll)
| Exception | Condition |
|---|---|
| ArgumentException | When setting this property, the specified value is not of type Type. |
This property is very similar to the TargetType property of the Style class. When you set this property to the data type without specifying an x:Key, the DataTemplate gets applied automatically to data objects of that type. Note that when you do that, the x:Key is set implicitly. Therefore, if you assign this DataTemplate an x:Key value, you are overriding the implicit x:Key and the DataTemplate would not be applied automatically.
The DataType property is particularly useful when you bind to collections that contain objects of different types, as shown in the example code.
The following Silverlight 5 code example demonstrates how to use this property to apply data templates to items in a list depending on their type. In this example, an employee list includes some employees who are managers. A ListBox uses the templates to render the regular employees in normal type and the managers in bold type.
<Grid x:Name="LayoutRoot" Background="White"> <Grid.Resources> <local:EmployeeCollection x:Key="Employees"> <local:Employee Name="Employee1"/> <local:Manager Name="Manager1"/> <local:Employee Name="Employee2"/> <local:Manager Name="Manager2"/> </local:EmployeeCollection> </Grid.Resources> <ListBox ItemsSource="{StaticResource Employees}"> <ListBox.Resources> <DataTemplate DataType="local:Employee"> <TextBlock Text="{Binding Name}"/> </DataTemplate> <DataTemplate DataType="local:Manager"> <TextBlock FontWeight="Bold" Text="{Binding Name}"/> </DataTemplate> </ListBox.Resources> </ListBox> </Grid>
For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.