簡體   English   中英

如何使用多個DataContext

[英]How to use more than one DataContext

我正在使用MVVM Light,在我的定位器中有兩個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}">

據我所知,您沒有使用2 DataContext 您使用一個DataContext 2個對象。 DataContext設置為Locator (不帶任何Path ),然后Path=SettingsVM.PropertyC每個綁定指定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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM