c# - MVVM 导航 ViewModel

标签 c# wpf mvvm

我对 C# 比较陌生,正在学习这里的 MVVM 教程 https://www.tutorialspoint.com/mvvm/mvvm_hierarchies_and_navigation.htm

我在使用 MainWindowViewModel 时遇到问题

class MainWindowViewModel : BindableBase {

    public MainWindowViewModel( ) {
        NavCommand = new MyICommand<string>(OnNav);
    }

    private CustomerListViewModel custListViewModel = new CustomerListViewModel( );

    private OrderViewModel orderViewModelModel = new OrderViewModel( );

    private BindableBase _CurrentViewModel;

    public BindableBase CurrentViewModel {
        get { return _CurrentViewModel; }
        set { SetProperty(ref _CurrentViewModel, value); }
    }

    public MyICommand<string> NavCommand { get; private set; }

    private void OnNav(string destination) {

        switch (destination) {
            case "orders":
                //CurrentViewModel = orderViewModelModel;
                break;

            case "customers":
            default:
                //CurrentViewModel = custListViewModel;
                break;
        }
    }
}

我无法使用以上两行设置 CurrentViewModel 取消注释来构建应用程序。我得到:

  • 无法将类型“MVVMHierarchiesDemo.ViewModel.OrderViewModel”隐式转换为“MVVMHierarchiesDemo.BindableBase”

  • 无法将类型“MVVMHierarchiesDemo.ViewModel.CustomerListViewModel”隐式转换为“MVVMHierarchiesDemo.BindableBase”

我确实在前面的 (tutorualspoint) 教程中发现了错字/错误,但在层次结构教程中没有发现任何错误。

示例中是否存在我没​​有发现的问题?

最佳答案

您的 CurrentViewModel 属性属于 BindableBase 类型,因此您要分配给它的任何对象都应该是 BindableBase 或派生自它.

这就是为什么您必须将 : BindableBase 添加到类 CustomerListViewModelOrderViewModel 中的原因:

class OrderViewModel : BindableBase
{
    //whatever
}

关于c# - MVVM 导航 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41540528/

相关文章:

c# - Delegate.DynamicInvoke 太慢,如何将调用更改为 Invoke?

c# - 在网格上显示网格线

c# - Unity 2D项目结构: How to create Player dynamically based on script

wpf - 如何将 UserControl 添加到 WPF 窗口上的面板

wpf - 可以让 MVVM 没有临时模型的模型吗?

android - 使用 LiveData 时,为什么要在 ViewModel 类中双重声明变量?

c# - 为 asp.net 网站运行简单的脚本

c# - 使用派生类中的其他类型来抽象定义默认行为

c# - MVVM绑定(bind)很多属性

c# - 在 WPF 应用程序中激活 Dragon Naturally Speaking Full-Text Control 功能