Reputation: 6675
I'm reading Mark Seeman's book "Dependency Injection in .NET" again. In it he describes an adapter type used to provide the view with the appropriate view model, but in the same context also mentions making the view model aware of the view (though something like IWindow) to "control its windowing environment, such as showing modal dialog boxes."
It has been my experience that this is a non-trivial breach of MVVM design, and may even be a poor DI solution. Most of these sorts of "needs" are often capable of being expressed through a combination of DataTriggers, third party services, mediator patterns, and in some cases, plain old clr events. (It's worth noting that many people prefer exposing eventlike ViewModel elements through IObserver injection. Mark Seeman even blogged on this!
Therefore I ask the question: "Regardless of framework, technology, language, stack, or toolset. If MVVM can be implemented, is there (should there ever be) ANY reason that the View Model need awareness of the view?"
Followup related question: "Is there ever justification for ignoring this guidance due to complexity of enforcing the pattern strictly?"
Upvotes: 2
Views: 1001
Reputation: 163
Regardless of framework, technology, language, stack, or toolset. If MVVM can be implemented, is there (should there ever be) ANY reason that the View Model need awareness of the view?
A ViewModel is the model for the View, not the other way around, so there should not be any awareness (either directly or through an interface) of the View in the ViewModel. The only time I've seen that the ViewModel should be made aware of the View, was because of bad design.
Is there ever justification for ignoring this guidance due to complexity of enforcing the pattern strictly?
I don't think there is.
A lot of ViewModels look like as if the developers did everything first in the code-behind and then moved all that code-behind logic in a separate class and called it the ViewModel. You'll see things there like opening popups or deciding how wide a certain control should be.
I think that this is not the way to get the most out of MVVM. UI logic will always be linked to the View. If you use WPF or Silverlight it will be very difficult to get rid of all code in the code-behind.
E.g. showing a modal dialog box is not the responsibility of the ViewModel, it is the UI that decide how to represent a certain condition/event. The condition/event can be found in the ViewModel, but changes to this will be handled by the View.
Upvotes: 3