Compartir a través de


DataTemplate.DataType Property

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Gets or sets the type for which this DataTemplate is intended.

Namespace:  System.Windows
Assembly:  System.Windows (in System.Windows.dll)

Syntax

'Declaration
Public Property DataType As Type
public Type DataType { get; set; }

Property Value

Type: System.Type
The type of object to which this template is applied.

Exceptions

Exception Condition
ArgumentException

When setting this property, the specified value is not of type Type.

Remarks

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.

Examples

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>
Public Class Employee
    Public Property Name As String
End Class

Public Class Manager
    Inherits Employee
End Class

Public Class EmployeeCollection
    Inherits ObservableCollection(Of Employee)
End Class
public class Employee { public string Name { get; set; } }
public class Manager : Employee { }
public class EmployeeCollection : ObservableCollection<Employee> { }

Version Information

Silverlight

Supported in: 5

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.