【问题标题】:How should a Model get passed into the ViewModel?模型应该如何传递到 ViewModel 中?
【发布时间】:2023-04-02 11:15:01
【问题描述】:

在 MVVM 设计中,假设如果 View 创建了 ViewModel,ViewModel 应该如何知道它的 Model?

我从几个地方了解到模型可以通过其构造函数传递给 ViewModel。所以它看起来像:

class ViewModel {
   private Model _model;
   public ViewModel(Model model) {
      _model = model;
   }
}

由于 View 正在创建 ViewModel,并将 Model 传递给 ViewModel 的构造函数,因此 View 必须知道 Model。但从我从大多数 MVVM 设计中看到的 UML 图来看,View 似乎对 Model 一无所知。

模型应该如何传递到 ViewModel 中?

【问题讨论】:

    标签: c# design-patterns mvvm


    【解决方案1】:

    你几乎走在了正确的轨道上,你只是错过了一条重要的信息。

    是的,可以将模型传递给构造函数上的视图模型 - 这称为依赖注入,或者称为 Inversion of Control (IoC)。

    最简单的方法是使用 Prism 中的 UnityContainer。在应用程序启动时的某个地方,您在统一容器中注册接口及其相应的实现类型,从那时起,您在 Unity 容器上调用 Resolve<MyInterface>() 以获取与该实例关联的类型的物理实例。

    Unity 真正能帮到你的地方在于,当你告诉它解析一个类型时,它会自动解析尽可能多的构造函数参数。因此,如果您的视图模型上的构造函数如下所示:

    public class MyViewModel : IMyViewModel
    {
        public MyViewModel(IUnityContainer container, IMyModel model)
        {
            _container = container;
            _model = model;
            ...etc...
        }
    }
    

    你的观点是这样的:

    this.DataContext = container.Resolve<IMyViewModel>();
    

    然后,统一容器将新建 MyViewModel 类的实例,因为它还将解析并新建与 IMyModel 关联的类的实例。

    【讨论】:

    • 谢谢!我没有使用 Prism 和 UnityContainer。从您提到的内容来看,这个想法似乎是在 ViewModel 的构造函数中为模型使用接口。但是在这种情况下,ViewModel 怎么知道 Model 内部的方法和数据呢?模型的接口会是一个通用接口,比如所有模型都实现的IModel,还是每个模型都有一个单独的接口,比如MyFirstModel,有IMyFirstModel,对于MySecondModel,有@987654330 @等等?
    猜你喜欢
    • 2018-12-25
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多