DataTemplate DataType用法WPF

编程入门 行业动态 更新时间:2024-10-21 19:45:14
本文介绍了DataTemplate DataType用法WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在像这样设置UserControls的DataContext:

I had been setting the DataContext for UserControls like so:

<uc:DepartmentListingView DataContext="{Binding ., Mode=TwoWay}" />

基于 Josh Smith的示例项目我正在尝试使用DataTemplate和DataType完成相同的操作:

Based on a sample project by Josh Smith I am trying to accomplish the same thing with a DataTemplate and DataType:

<!-- Template applies a DepartmentListingView to an instance of the DepartmentSelectionViewModel class. --> <DataTemplate DataType="{x:Type model:DepartmentSelectionViewModel}"> <uc:DepartmentListingView /> </DataTemplate>

这很好,但是当然存在问题;我认为可能是由于尝试将多个视图(UserControl)设置为同一视图模型(?)而引起的。在下面的代码中,我现在将上方的同一viewModel与同一窗口中的其他视图相关联。

This works well, but of course there is a problem; I think it might arise from trying to set more than one view (UserControl) to the same view model(?). In the code below I am now associating the same viewModel from above with a different view in the same window.

<DataTemplate DataType="{x:Type model:DepartmentSelectionViewModel}"> <uc:ListSubjectHeaderView /> </DataTemplate>

第一个视图的连线与我显式设置DataContext时的连线相同,但最后一个视图没有绑定,尽管控制台中也没有明显的DataBinding错误。

The first view is wired the same as it was when I set the DataContext explicitly but the last view gets no binding, although no obvious DataBinding error in the console either.

因此,以这种方式重用DataType / DataTemplate会成为问题吗?

So, would resusing the DataType / DataTemplate trick this way be the problem?

谢谢, Berryl

Thanks, Berryl

推荐答案

理想情况下,您将拥有一个视图和视图模型之间的一种关系。

Ideally you will have a one to one relationship between a view and viewmodel.

要获得想要的内容,可能不需要额外添加子视图类并将其作为数据模板中的数据类型。

To get what you want perhaps subclass your viewmodel with nothing extra and have that subclassed viewmodel as the datatype in the datatemplate.

那样,仅创建正确的视图模型将驱动正确的数据模板,并因此驱动用户控制

That way just creating the correct viewmodel will drive the correct datatemplate and therefore usercontrol

更多推荐

DataTemplate DataType用法WPF

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

发布评论

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

>www.elefans.com

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