如何使用多个DataContext

时间:2014-11-17 14:20:22

标签: c# xaml mvvm windows-phone viewmodel

我正在使用MVVM Light,在我的Locator中我有两个ViewModel。但是在页面中我想使用多个ViewModel在页面的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}">

1 个答案:

答案 0 :(得分:0)

据我所见,你不使用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>