[英]Multiple Data Contexts in View
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.
它们根据用户做出的类似向导的选择而变为活动状态。
The easiest solution I've found is to have one ViewModel which holds the other ViewModels as Properties
. 我找到的最简单的解决方案是拥有一个ViewModel,将另一个ViewModels保留为
Properties
。 Then the View can access the properties he wants from all the different ViewModels... 然后,View可以从所有不同的ViewModels访问他想要的属性。
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 DataContext
to an instance of a VMContainer
which you already set the specific VM properties in... 现在,在您的视图中,将
DataContext
设置为VMContainer
的实例,您已经在其中设置了特定的VM属性。
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 have to create a brand new VMContainer
class just for this. 值得一提的是,你不必创建一个全新的
VMContainer
类只是这一点。 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) 您也可以仅在现有VM中为该其他VM添加新属性(如果可能/基于您的VM表示的逻辑)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.