DataTemplate DataType用法WPF [英] DataTemplate DataType usage WPF

查看:353
本文介绍了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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