我使用 ContentPresenter 来捕捉内容。在窗口中,我放了这样的东西:
<ContentPresenter Content="{Binding MainContent}" />
在视图模型中,我有一个名为 MainContent 的对象类型的属性:
public object MainContent { get { return (object)GetValue(MainContentProperty); } set { SetValue(MainContentProperty, value); } }
public static readonly DependencyProperty MainContentProperty = DependencyProperty.Register("MainContent", typeof(object), typeof(SomeViewModel), new FrameworkPropertyMetadata(null));
无论您将 MainContent 设置为什么,都将显示在窗口中。
为了保持视图和视图模型之间的分离,我通常将 MainContent 属性设置为另一个视图模型并使用数据模板将该视图模型映射到视图:
<DataTemplate DataType="{x:Type viewmodels:PlanViewModel}">
<views:PlanView />
</DataTemplate>
我将该数据模板与一堆其他视图模型到视图映射器一起放在一些中央资源字典中。