4

When I am creating a Resource we are specifying the DataType inside it:

<Window.Resources>
    <DataTemplate x:Key="StudentView"
                  DataType="this:StudentData">
          <TextBox Text="{Binding Path=StudentFirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                   Grid.Row="1"
                   Grid.Column="2"
                   VerticalAlignment="Center" />
          <TextBox Text="{Binding Path=StudentGradePointAverage}"
                   Grid.Row="2"
                   Grid.Column="2"
                   VerticalAlignment="Center" />
    </DataTemplate>
<Window.Resources>

And while binding :

<ItemsControl ItemsSource="{Binding TheStudents}"
              ItemTemplate="{StaticResource StudentView}">

So why are we using the DataType, even if I remove the DatType , my sample runs fine. Is it restricting certain types , that can be inside DataTemplete?

But I tried binding one of the TextBox with a garbage value (Not present in the View-Model) and it works fine!

H.B.
  • 166,899
  • 29
  • 327
  • 400
Simsons
  • 12,295
  • 42
  • 153
  • 269
  • One advantage is that knowing the expected data context type allows for some static verification of whether binding paths are valid. It's also a documentation hint to future developers of the intention of the DataTemplate. – Dan Bryant Jul 11 '12 at 14:24

1 Answers1

12

The DataType is for implicit application, if you drop the x:Key you do not need to reference it in the ItemsControl.ItemTemplate for example. Read the documentation.

This property that 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.

H.B.
  • 166,899
  • 29
  • 327
  • 400