【问题标题】:MVVM navigating ViewModelsMVVM 导航 ViewModel
【发布时间】:2017-01-09 03:18:48
【问题描述】:

我对 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”

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

是否存在我在示例中没有看到的问题?

【问题讨论】:

  • 你确定你让CustomerListViewModelOrderViewModel 类派生自BindableBase 吗?
  • 谢谢。一次有很多概念,我总是被小事卡住。
  • 欢迎您。

标签: c# wpf mvvm


【解决方案1】:

我不知道为什么,但你可以试试。

  • 在 CustomerListViewModel.cs 中

    类 OrderViewModel :BindableBase

    {

    }

  • 在 OrderViewModel.cs 中

    类 OrderViewModel :BindableBase

    {

    }

【讨论】:

  • 可能是因为他试图将这些分配给CurrentViewModel,而这BindableBase
【解决方案2】:

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

这就是为什么您必须将: BindableBase 添加到您的课程CustomerListViewModelOrderViewModel 中:

class OrderViewModel : BindableBase
{
    //whatever
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 2017-04-08
    • 2015-09-01
    • 2022-12-11
    相关资源
    最近更新 更多