如何在 WPF 应用程序中结合 MVVM 和依赖注入? [英] How can I combine MVVM and Dependency Injection in a WPF app?
问题描述
您能否举例说明您将如何使用(您最喜欢的)DI 框架为 WPF 应用程序连接 MVVM 视图模型?
Can you please give an example of how you would use (your favorite) DI framework to wire MVVM View Models for a WPF app?
您是否会创建视图模型的强连接层次结构(例如,每个嵌套控件的 ViewModel 都是父级 ViewModel 上的一个属性,并且您在 XAML 中将其绑定到嵌套控件的 DataContext),或者您会使用某种甚至更多-抽象的视图模型"管理器,它维护着一些弱连接的层次结构......就像在 CAB 中一样,也许?
Will you create a strongly-connected hierarchy of View Models (like where every nested control's ViewModel is a property on a parent's ViewModel and you bind it to nested control's DataContext in XAML) or you would use some kind of even-more-abstract ""View Model" Manager", which maintains some weakly-connected hierarchy... like in CAB, maybe?
推荐答案
如果一个视图模型只能与另一个视图模型一起存在,我会创建一个牢固的关系.也就是说,拥有视图模型将直接引用一个或多个从属视图模型.另一方面,如果视图模型应该能够存在或不存在另一个视图模型,我会采用松散耦合的方法,它们通过事件总线进行通信.
If a view model can only exist in conjunction with another, I create a strong relationship. That is the owning view model will have a direct reference to one or more of the dependent view models. If, on the other hand, a view model should be able to exist with or without another, I take a loosely-coupled approach where they communicate via an event bus.
就使用 DI 和 MVVM 而言,您绝对可以将两者结合起来.就这么简单:
In terms of using DI with MVVM, absolutely you can combine the two. It's as simple as:
public class MyViewModel
{
private readonly IMyDependency _myDependency;
public MyViewModel(IMyDependency myDependency)
{
_myDependency = myDependency;
}
}
但是请注意,这假定了 MVVM 的视图模型优先"方法,这有其缺点.
Note, however, that this assumes a "view model first" approach to MVVM, which has its drawbacks.
这篇关于如何在 WPF 应用程序中结合 MVVM 和依赖注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!