WPF MVVM切换用户控件

Chr*_*ris 4 c# wpf user-controls mvvm

我是MVVM和WPF的新手,但我知道MVVM中发生了什么.我在主窗口中切换用户控件时遇到问题.在我的应用程序中,我有:MainWindow.xaml,带有日志和2个链接:显示全部并创建新的.当然我有ViewModel.我还有2个UserControls:ShowAll和Create with ViewModels以及其中的所有逻辑(添加数据等).当我单击链接时创建新建或单击ShowAll时显示全部,如何显示创建表单?

在windowForms我只是隐藏UC,但是这里没有代码:)

我的MainWindow.xaml:

<Window x:Class="Test.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="300" Width="300">
    <Grid>
        <StackPanel>
            <TextBox Text="{Binding Name}"/>
            <Button Content="Change" Command="{Binding ChangeCommand}"/>
        </StackPanel>
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

我的MainWindowViewModel:

class MainWindowViewModel : BaseViewModel
{
    private Person _person;
    private BaseCommand _changeCommand;

    public MainWindowViewModel()
    {
        _person = new Person();
    }

    public string Name
    {
        get
        {
            return _person.Name;
        }
        set
        {
            if (_person.Name != value)
                _person.Name = value;
            OnPropertyChanged(() => Name);
        }
    }

    public ICommand ChangeCommand
    {
        get
        {
            if (_changeCommand == null)
                _changeCommand = new BaseCommand(() => change());
            return _changeCommand;
        }
    }

    private void change()
    {
        _person = new Person();
        Name = _person.Imie;
    }
}
Run Code Online (Sandbox Code Playgroud)

在Create和ShowAll中没有代码.在xaml中只有一个标签,VM是空的.只是为了测试.

感谢帮助!

Slu*_*art 8

您可以使用a ContentControl来显示DataTemplate基于绑定到的ViewModel类型的特定内容ContentControl.

http://www.japf.fr/2009/03/thinking-with-mvvm-data-templates-contentcontrol/

绑定到ShowAll按钮的命令可以简单地更改主ViewModel上的属性,该属性绑定到内容控件.