I'm applying the MVVM pattern to my application that will have dozens of screens (with the respectives ViewModels). Now I'm stuck in a very simple point ... who has the responsibility to create the new window, instantiate the viewModel and assign one to another?
I think is wrong to do this in the View or even in the ViewModel. I saw many replies advising the use of external frameworks, that is not an option to me.
What do you think?
What is the official Windows recommendation?
Let's try an example: the user clicks a button and a confirmation dialog box is shown with Yes/No. Normally you would raise the notification in the event handler of the button:
Now, since we have MVVM, the business logic (here the
if/else
) must be moved into the ViewModel. But the UI must remain on the UI control! Suppose this is the ViewModel:The ViewModel can't own the UI... but can own an ABSTRACTION of the interaction required with the user.
This may be the interface of the interaction:
So the ViewModel can have a property like this:
VM
does not instantiate it,VM
accepts an instance of the interface passed by someone else. For example in the constructor:So its method can become:
And the UI? You can create a concrete interaction that uses UI elements:
Do you see the point? We have saved the pattern: the ViewModel acts with the logic, putting together different abstractions, but knows nothing about the implementations, about message boxes, buttons, etc.. You can implement those interactions as UI interactions, for example in the constructor of the UI Control that owns the
VM
:But you can also implement them as automatic results, for example when you want to run a test list trying a default answer of "yes" or a default answer of "no":
This is called "dependency injection". try it on Google, you can find dozens of tutorials. In this case, I've build a dependency injection by constructor.
This is a solid way in which you can build manually all the bridges between the UI controls, through the ViewModels, but preserving the pattern.
this is what i do:
the mainviewmodel compose the modules via MEF.