简体   繁体   中英

How to use more than one DataContext

Im using MVVM Light, and in my Locator I have two ViewModels. However in a page I want to use more than one ViewModels to use their properties in the page's ui elements, but how?

Here is the XAML of my Page:

<Page
x:Class="my_app.MainMenuPage"
xmlns:i="using:Microsoft.Xaml.Interactivity"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:my_app"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Foreground="Red"
DataContext = "{Binding Source={StaticResource Locator}, Path=SettingsVM }">

Here is the code of my Locator:

public class ViewModelLocator
{
    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

        SimpleIoc.Default.Register<StudentsViewModel>();
        SimpleIoc.Default.Register<SettingsViewModel>();
    }

    public StudentsViewModel StudentsVM
    {
        get
        {
            return ServiceLocator.Current.GetInstance<StudentsViewModel>();
        }
    }

    public SettingsViewModel SettingsVM
    {
        get
        {
            return ServiceLocator.Current.GetInstance<SettingsViewModel>();
        }
    }

    public static void Cleanup() {}
}

So i can't do something like this, obviously:

DataContext = "{Binding Source={StaticResource Locator}, Path=SettingsVM, Path=StudentsVM}">

As far as I can see you don't use 2 DataContext . You use 2 objects of one DataContext . Set DataContext to Locator (without any Path ) and then specify Path=StudentsVM.PropertyA or Path=SettingsVM.PropertyC per binding

<Page ... DataContext="{Binding Source={StaticResource Locator}}">
   <!-- .... -->
   <TextBlock Text="{Binding StudentsVM.PropertyA}"/>
   <TextBlock Text="{Binding StudentsVM.PropertyB}"/>
   <TextBlock Text="{Binding SettingsVM.PropertyC}"/>
   <TextBlock Text="{Binding SettingsVM.PropertyD}"/>
   <!-- .... -->
</Page>

or if you have more properties to bind you can locally change DataContext for group of controls

<Page ... DataContext="{Binding Source={StaticResource Locator}}">
   <!-- .... -->
   <StackPanel DataContext="{Binding StudentsVM}">
       <TextBlock Text="{Binding PropertyA}"/>
       <TextBlock Text="{Binding PropertyB}"/>
   </StackPanel>
   <!-- .... -->
   <StackPanel DataContext="{Binding SettingsVM}">
       <TextBlock Text="{Binding PropertyC}"/>
       <TextBlock Text="{Binding PropertyD}"/>
   </StackPanel>
   <!-- .... -->
</Page>

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