简体   繁体   中英

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

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:

<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 . Then the View can access the properties he wants from all the different ViewModels...

To illustrate, you can have a 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...

Then you can do something like this in 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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM