Why should we use DataTemplate.DataType

佐手、 提交于 2019-12-07 08:06:07

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/11433802/why-should-we-use-datatemplate-datatype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!