【问题标题】:MVVM Light Apuntas Notas CategoryEditorViewModel constructorMVVM Light Apuntas Notas CategoryEditorViewModel 构造函数
【发布时间】:2012-12-27 21:14:58
【问题描述】:

我已经下载并运行了该示例并了解了大部分内容,除了我无法弄清楚 CategoryEditorViewModel 类从哪里获取它的构造函数参数。它是“ICategoryRepository categoryRepository”,我搜索了参考资料,但仍然无法理解创建视图模型时参数的传递方式和位置。 我希望有人能帮我解答。

【问题讨论】:

    标签: c# wpf mvvm light


    【解决方案1】:

    我也有同样的问题。

    就我从类似的线程中得出的结论而言

    Constructors with multiple parameters

    更多的是,在 bootstrap.cs 文件中的 Apuntas Notas 项目中,接口 ICategoryRepository 已注册到 CategoryRepository 类。

    因此,当属性CategoryEditor 尝试通过解析 ViewModelLocator.cs 中的实例时

            public CategoryEditorViewModel CategoryEditor
        {
            get { return _bootStrapper.Container.Resolve<CategoryEditorViewModel>(); }
        }
    

    并且实例不存在,它尝试使用其唯一的构造函数创建该类CategoryEditorViewModel 的对象,该构造函数需要ICategoryRespository 接口。

    正如我之前提到的,我们在 bootstrap.cs 文件中使用CategoryRepository 类注册了这个接口。因此,它创建了一个 CategoryRepository 对象并将其传递给视图模型构造函数。

    希望这能消除您的疑虑。

    哦,如果你想知道如果你有多个构造函数会发生什么,你可以通过在 bootstrap.cs 中注册一个你喜欢的类似

    Container.RegisterType<CategoryEditorViewModel>(new InjectionConstructor(typeof(ICategoryRepository), 5));
    

    现在,如果 CategoryEditorViewModel 中有另一个构造函数还需要一个 int,则将调用该构造函数,而不是之前的构造函数。 (传递一个 5 的 int 值很愚蠢,但希望你能明白,你可以在那里为你的首选构造函数提供参数的类型,并确保它们也注册到引导容器中)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      • 2015-04-04
      • 2015-06-05
      • 1970-01-01
      • 2014-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多