我使用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>
我将那个数据模板与其他视图模型到视图映射器一起放在一个中央资源字典中。