更改视图,在MVVM [英] Changing a view in the MVVM

查看:163
本文介绍了更改视图,在MVVM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的主窗口具有以下code:

If my MainWindow has the following code:

<Window x:Class="DaveMVVM.View.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:viewModel ="clr-namespace:DaveMVVM.ViewModel"
        xmlns:view="clr-namespace:DaveMVVM.View"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.Resources>
            <viewModel:MainWindowViewModel x:Key="Vm" />
        </Grid.Resources>        
        <view:MyFirstView />        
    </Grid>   
</Window>

那么我可以假设我不能改变从MyFirstView查看...例如,我会想我的主窗口仅仅是这实际上只承载菜单,并根据他们从菜单选择哪个选项取决于所显示的内容查看。

then can I assume I can't change the View from MyFirstView... For example, I will want my MainWindow to just be a frame which practically only hosts the Menu, and depending on what option they select from the Menu will depend on what View is displayed.

所以,我的2个问题是

1)我是正确的思维,上面的例子不会因为查看工作很辛苦codeD。
2)我必须用这必将对我MainWindowViewModel的DataTemplates,然后为每个视图创建一个DataTemplate?

1) Am I correct in thinking that the above example will not work since the View is hard coded.
2) Do I have to use DataTemplates which are bound to my MainWindowViewModel, and then have a DataTemplate created for each View?

感谢你。

推荐答案

您会做如下:

您MainWindowViewModel公开的属性 CurrentContent 。它返回所有视图模型的一个共同的基本类型:

Your MainWindowViewModel exposes a property CurrentContent. It returns a common base type of all your view models:

public ViewModelBase CurrentContent
{
    get { return _currentContent; }
    private set
    {
        if(value == _currentContent)
            return;

        _currentContent = value;
        RaisePropertyChanged("CurrentContent");
    }
}

根据用户的选择,你会该属性设置为相应的视图模型。

Based on the selection of the user, you would set that property to the corresponding view model.

您主视图中会包含一个 ContentControl中绑定到该属性:

Your main view would contain a ContentControl that is bound to this property:

<ContentControl Content="{Binding CurrentContent}" />

最后,您的视图 - 或单独的资源字典 - 将必须包含数据模板用于每个可能的内容视图-模型:

Finally, your view - or a separate resource dictionary - would have to contain data templates for each of the possible content view-models:

<DataTemplate DataType="{x:Type MyFirstViewModel}">
    <view:MyFirstView /> 
</DataTemplate>
<DataTemplate DataType="{x:Type MySecondViewModel}">
    <view:MySecondView /> 
</DataTemplate>

这篇关于更改视图,在MVVM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆