如何使用多个数据上下文

本文关键字:数据 上下文 何使用 | 更新日期: 2023-09-27 18:30:36

我使用 MVVM Light,在我的定位器中,我有两个 ViewModels。但是,在一个页面中,我想使用多个 ViewModels 在页面的 ui 元素中使用它们的属性,但是如何呢?

这是我页面的 XAML:

<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 }">

这是我的定位器的代码:

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() {}
}

所以我不能做这样的事情,显然:

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

如何使用多个数据上下文

我所知,您不使用 2 DataContext.您使用一个DataContext的 2 个对象。将DataContext设置为 Locator(不带任何Path),然后为每个绑定指定Path=StudentsVM.PropertyAPath=SettingsVM.PropertyC

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

或者,如果要绑定更多属性,则可以在本地更改控件组的DataContext

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