在创建资源时,我们在其中指定数据类型:
< 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
发布评论