我们为什么要使用DataTemplate.DataType [英] Why should we use DataTemplate.DataType

查看:387
本文介绍了我们为什么要使用DataTemplate.DataType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 < 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,即使我删除了DatType,我的示例也可以正常运行。



但是我尝试将其中一个文本框与垃圾值绑定(在视图模型中不存在)吗?



工作良好!

解决方案

DataType 用于隐式应用程序,如果您删除 x:Key ,例如,您无需在 ItemsControl.ItemTemplate 中引用它。阅读文档


此属性与 TargetType 属性= noreferrer>样式类。当您将此属性设置为数据类型而未指定 x:Key 时,数据模板会自动应用于该类型的数据对象。请注意,这样做时会隐式设置 x:Key 。因此,如果您为此 DataTemplate x:Key 值,您将覆盖隐式的 x:Key DataTemplate 不会自动应用。



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!

解决方案

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.

这篇关于我们为什么要使用DataTemplate.DataType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆