视图中的多个数据上下文 [英] Multiple Data Contexts in View

查看:87
本文介绍了视图中的多个数据上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试过几次以在帖子中找到答案,但尚未找到答案(至少在我了解以来,对于WPF来说还很新).

I have tried a few times to find an answer in the posts but not found yet (at least in what I understand since fairly new to WPF).

我在视图构造函数中定义了一个数据上下文:

I define a Data Context in the view constructor:

this.DataContext = viewModel;

如果可能,我想在单个视图中使用多个数据上下文吗?我听到其他人对此有多个不一致的答案.目的是我需要访问多个视图模型中的属性.例如,在如下所示的情况下,将使用我的视图XAML:

I would like to use multiple data contexts in a single view if possible? I have heard multiple inconsistent answers to this from others. The goal is that I need access to properties in multiple view models. For example my view XAML is used in cases like that shown below:

<MultiBinding Converter="{StaticResource multiBooleanToVisibilityConverter}">
                <Binding Path="ResultControlsVisibileByDefault" UpdateSourceTrigger="PropertyChanged"/>
                <Binding Path="StarWidthValueList.Count" UpdateSourceTrigger="PropertyChanged"/>
            </MultiBinding>

如果我能在适当的视图模型中显式引用每个属性,那就太好了.

It would be great if I could explicitly reference each property in the appropriate view model.

注意:在主窗口中有多个基于窗口的视图模型.它们会根据用户做出的类似向导的选择而变为活动状态.

Note: there are multiple view models based on windows that were overlaid in the main window. They become active based on wizard-like selections made by the user.

推荐答案

我找到的最简单的解决方案是拥有一个ViewModel,将另一个ViewModel保留为Properties.然后,View可以从所有不同的ViewModels中访问他想要的属性...

The easiest solution I've found is to have one ViewModel which holds the other ViewModels as Properties. Then the View can access the properties he wants from all the different ViewModels...

为说明起见,您可以拥有一个VMContainer:

To illustrate, you can have a VMContainer:

public class VMContainer
{
    public FirstViewModel   VM1 { get; set; }
    public SecondViewModel  VM2 { get; set; }
}

现在在您的视图中将DataContext设置为VMContainer的实例,您已经在其中设置了特定的VM属性.

Now in your view set your DataContext to an instance of a VMContainer which you already set the specific VM properties in...

然后您可以在XAML中执行类似的操作

Then you can do something like this in XAML

<Textbox Text="{Binding VM1.SomePropertyInFirstViewModel}" />
<Textbox Text="{Binding VM2.SomePropertyInSecondViewModel}" />

值得注意的是,您没有为此专门创建全新的VMContainer类.您也可以只在现有VM中为该其他VM添加新属性(如果可能/根据您的VM表示的逻辑)

It's worth noting that you don't have to create a brand new VMContainer class just for this. You can also just add a new property in an existing VM for that other VM (if it's possible/logical based on what your VM represents)

这篇关于视图中的多个数据上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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