WPF中切换用户控件只显示ViewModel的名称

Switching user control in WPF only shows the name of ViewModel

我使用 MVVM 设计和一些简单的导航构建了 WPF 应用程序。我向项目添加了两个视图(用户控件)和虚拟 ViewModel(空 classess)以通过此导航切换它们。这是我的文件夹结构: Folder Structure

所以当我点击 navi 中的第一个按钮而不是用户控件的视图时,我得到了 ViewModel 的名称,如下所示: App screen (View.ViewModels.NameoftheViewModel)

我是这样实现的:

Window.Resources with DataTemplate

Navi buttons for switching user controls

MainWindow.xaml.cs :

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new NavigationViewModel();
    }

用于切换的NavigationViewModel :

class NavigationViewModel : INotifyPropertyChanged
{
    public ICommand CurrencyCommand { get; set; }
    public ICommand GoldCommand { get; set; }
    private object selectedViewModel;
    public object SelectedViewModel
    {
        get { return selectedViewModel; }
        set { selectedViewModel = value; OnPropertyChanged("SelectedViewModel"); }
    }

    public NavigationViewModel()
    {
        CurrencyCommand = new BaseCommand(OpenCurrency);
        GoldCommand = new BaseCommand(OpenGold);
    }

    public void OpenCurrency(object obj)
    {
        SelectedViewModel = new CurrencyViewModel();
    }

    public void OpenGold(object obj)
    {
        SelectedViewModel = new GoldViewModel();
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propName)

    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }

    }
}

BaseCommand class 简单地实现了 ICommand 接口。

XAML 用于显示用户控件:

<ContentControl Margin="45, 50, 0, 0" Content="{Binding SelectedViewModel}"/>

有谁知道为什么会这样?我从教程中做到了这一点:Tutorial link 并且在本教程案例中一切正常,但在我的项目中却没有。

来自链接教程:

Create a DataTemplate of type EmployeeViewModel and it should contain EmployeeView UserControl inside it. Important thing is you should specify any key to the DataTemplates, since these DataTemplates are going to get queried by their DataType.

不应该为视图模型的数据模板指定x:Key。只有在没有 x:Key

的情况下,DataTemplates 才能按 DataType 选取
<DataTemplate DataType="{x:Type vm:CurrencyViewModel}">
    <vs:CurrencyControl/>
</DataTemplate>