正如我在评论中提到的,不可能将单个视图与多个(同一级别)视图模型直接连接起来。
您必须将您的视图拆分为一个主视图和(多个)子视图(在 XAML 中逻辑上或通过将子视图移动到单独的 UserControls 中物理上)。
这是我的建议。
- 使用 PRISM 区域。
定义一个包含区域的主视图:
<Window>
<StackPanel Orientation="Vertical">
<ContentControl prism:RegionManager.RegionName="Region1"/>
<ContentControl prism:RegionManager.RegionName="Region2"/>
</StackPanel>
</Window>
创建将“插入”(在 PRISM 的术语中 - 注入)到您的主视图中的子视图:
<UserControl x:Class="UserControl1">
<Grid/>
</UserControl>
<UserControl x:Class="UserControl2">
<Grid/>
</UserControl>
最后,您必须在 PRISM 中注册您的视图,以便实例化它们:
// Obtain the region manager over DI
IRegionManager regionManager;
regionManager.RegisterViewWithRegion("Region1", typeof(UserControl1));
regionManager.RegisterViewWithRegion("Region2", typeof(UserControl2));
每个子视图都有自己的视图模型。您可以使用 PRISM 的视图模型定位器来自动连接它们。
- 使用数据模板。
你的主视图:
<Window>
<Window.Resources>
<DataTemplate DataType="vm:ViewModel1">
<v:UserControl1/>
</DataTemplate>
<DataTemplate DataType="vm:ViewModel2">
<v:UserControl2/>
</DataTemplate>
</Window.Resources>
<ItemsControl ItemsSource="{Binding Items}"/>
</Window>
将子视图模型添加到您的主视图模型的Items 集合中,WPF 将为您创建视图并自动连接视图模型。
class MasterViewModel : BindableBase
{
public IEnumerable<BindableBase> Items
{
get { return new[] { new ViewModel1(), new ViewModel2() }
}
}
当然,您可以使用 DI 来实例化您的视图模型。
- 使用“堆叠”视图模型。
类似这样的:
class MainViewModel : BindableBase
{
public ViewModel1 ViewModel1 { get; private set; }
public ViewModel2 ViewModel2 { get; private set; }
}
在您的主视图中,您必须相应地设置绑定。
<Window>
<StackPanel>
<TextBlock Text="{Binding ViewModel1.SomeValue}"/>
<TextBox Text="{Binding ViewModel2.SomeValue}"/>
</StackPanel>
</Window>