Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

c# - How can I combine MVVM and Dependency Injection in a WPF app?

Can you please give an example of how you would use (your favorite) DI framework to wire MVVM View Models for a WPF app?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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;
    }
}

Note, however, that this assumes a "view model first" approach to MVVM, which has its drawbacks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...