In an MVVM design, suppsoe if the View creates the ViewModel, how should the ViewModel know about its Model?
I read from a few places that the Model can be passed into ViewModel through its constructor. So it looks something like:
class ViewModel {
private Model _model;
public ViewModel(Model model) {
_model = model;
}
}
Since the View is creating the ViewModel, and to pass the Model into the ViewModel's constructor, then the View has to know about the Model. But from the UML diagrams that I see from most MVVM designs, the View doesn't seem to know anything about the Model.
How should a Model get passed into the ViewModel?
You are almost on the right track, you are just missing a crucial piece of information.
Yes, a model can be passed to a viewmodel on the constructor - this is known as dependency injection, or alternatively as Inversion of Control (IoC).
The absolutely easiest way to achieve this is to use the UnityContainer from Prism. Somewhere around the startup of your application you register interfaces and their corresponding implementing type with the unity container, from then on you call Resolve<MyInterface>()
on the Unity container to get a physical instance of the type associated with that instance.
Where Unity will really help you out is that it will automatically resolve as many constructor parameters as it possibly can when you tell it to resolve a type. So if your constructor on your viewmodel looks like this:
public class MyViewModel : IMyViewModel
{
public MyViewModel(IUnityContainer container, IMyModel model)
{
_container = container;
_model = model;
...etc...
}
}
and your view does this:
this.DataContext = container.Resolve<IMyViewModel>();
the unity container will then new up an instance of the MyViewModel class, as it does that it will also resolve and new up an instance of the class associated with IMyModel.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With