Why should we use DataTemplate.DataType

When I create a Resource, we specify a 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 when binding:

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

So why do we use DataType even if I delete DatType, my example works fine. Is this a limitation of certain types that may be inside a DataTemplete?

But I tried binding one of the TextBoxs to the garbage size (not present in the View-Model), and it works great!

+4
source share
1 answer

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

This property is very similar to the TargetType Style property. When you set this property to a data type without specifying x: Key , the DataTemplate is automatically applied to data objects of that type. Note that in this case x: The key is set implicitly. Therefore, if you set this DataTemplate to x: Key , you override the implicit x: Key and the DataTemplate will not be applied automatically.

+12
source

All Articles