我们为什么要使用DataTemplate.DataType

编程入门 行业动态 更新时间:2024-10-22 08:35:16
本文介绍了我们为什么要使用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

本文发布于:2023-11-07 05:30:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565669.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:要使   DataTemplate   DataType

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!