[英]How to use more than one DataContext
Im using MVVM Light, and in my Locator I have two ViewModels. 我正在使用MVVM Light,在我的定位器中有两个ViewModel。 However in a page I want to use more than one ViewModels to use their properties in the page's ui elements, but how?
但是,在页面中,我想使用多个ViewModel在页面的ui元素中使用它们的属性,但是如何?
Here is the XAML of my Page: 这是我的页面的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 }">
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
. 据我所知,您没有使用2
DataContext
。 You use 2 objects of one DataContext
. 您使用一个
DataContext
2个对象。 Set DataContext
to Locator
(without any Path
) and then specify Path=StudentsVM.PropertyA
or Path=SettingsVM.PropertyC
per binding 将
DataContext
设置为Locator
(不带任何Path
),然后Path=SettingsVM.PropertyC
每个绑定指定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>
or if you have more properties to bind you can locally change DataContext
for group of controls 或者如果您有更多要绑定的属性,则可以在本地更改控件组的
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.