为什么我们应该使用DataTemplate.DataType

4

当我创建一个资源时,我们在其中指定数据类型:

<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>

同时,在绑定时:

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

那么为什么我们要使用 DataType,即使我去掉 DataType,我的示例也可以正常运行。它是否限制了某些类型,可以放在 DataTemplate 中?

但是我尝试将其中一个文本框绑定到垃圾值(不在视图模型中)上,它也可以正常工作!


一个优点是,知道预期的数据上下文类型可以对绑定路径的有效性进行一些静态验证。这也是对未来开发人员DataTemplate意图的文档提示。 - Dan Bryant
1个回答

12
DataType 属性用于隐式应用,如果您省略了 x:Key,就不需要在 ItemsControl.ItemTemplate 中引用它。请查看文档

该属性与 Style 类的 TargetType 属性非常相似。当将此属性设置为数据类型并且没有指定 x:Key 时,DataTemplate 将自动应用于该类型的数据对象。请注意,这样做会隐式设置 x:Key。因此,如果给此 DataTemplate 分配一个 x:Key 值,则会覆盖隐式的 x:Key,并且该 DataTemplate 不会自动应用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接