C# 如何使用多个DataContext
我使用MVVM灯光,在我的定位器中有两个ViewModels。但是在一个页面中,我想使用多个ViewModels在页面的ui元素中使用它们的属性,但是如何使用呢 以下是我的页面的XAML:C# 如何使用多个DataContext,c#,xaml,mvvm,windows-phone,viewmodel,C#,Xaml,Mvvm,Windows Phone,Viewmodel,我使用MVVM灯光,在我的定位器中有两个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
<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 }">
据我所知,您没有使用2 DataContext。您使用一个DataContext的两个对象。将DataContext设置为不带任何路径的定位器,然后为每个绑定指定Path=StudentsVM.PropertyA或Path=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 = "{Binding Source={StaticResource Locator}, Path=SettingsVM, Path=StudentsVM}">
<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>
<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>