Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should we use DataTemplate.DataType

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!

like image 988
Simsons Avatar asked Dec 15 '22 21:12

Simsons


1 Answers

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.

like image 91
H.B. Avatar answered Jan 01 '23 18:01

H.B.