wpf 视图中的多个数据上下文

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15282235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 07:57:32  来源:igfitidea点击:

Multiple Data Contexts in View

c#wpfxamlbindingwpf-controls

提问by Buck

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).

我已经尝试过几次在帖子中找到答案,但还没有找到(至少在我对 WPF 相当陌生后的理解中)。

I define a Data Context in the view constructor:

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

this.DataContext = viewModel;

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:

如果可能,我想在单个视图中使用多个数据上下文?我从其他人那里听到了多个不一致的答案。目标是我需要访问多个视图模型中的属性。例如,我的视图 XAML 用于如下所示的情况:

<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.

注意:有多个基于覆盖在主窗口中的窗口的视图模型。它们根据用户所做的类似向导的选择而变得活跃。

回答by Blachshma

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...

我发现的最简单的解决方案是让一个 ViewModel 将其他 ViewModel 保存为Properties. 然后视图可以从所有不同的视图模型访问他想要的属性......

To illustrate, you can have a VMContainer:

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

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

Now in your view set your DataContextto an instance of a VMContainerwhich you already set the specific VM properties in...

现在,在您的视图中,将您DataContext的实例VMContainer设置为您已经在...

Then you can do something like this in XAML

然后你可以在 XAML 中做这样的事情

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

It's worth noting that you don't haveto create a brand new VMContainerclass 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)

值得注意的是你不具备创建一个全新的VMContainer类只是这一点。您还可以在现有 VM 中为该其他 VM 添加新属性(如果可能/逻辑基于您的 VM 所代表的内容)