Changing a view in the MVVM

2019-08-05 03:09发布

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>

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.

So, my 2 questions are

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?

Thank you.

标签: .net mvvm
1条回答
爷、活的狠高调
2楼-- · 2019-08-05 03:32

You would do this as follows:

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.

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>
查看更多
登录 后发表回答