I'm making the move from MVP to MVVM, and a little confused as to how best bind the ViewModel
to the Model
. I understand how we can leverage WPF's data binding infrastructure to route events between the View
and ViewModel
using ICommand
and INotifyPropertyChanged
interface, e.g., the View
:
public class MyView
{
public MyView()
{
InitializeComponent();
DataContext = new MyViewModel();
}
}
and the ViewModel
:
public class MyViewModel : INotifyPropertyChanged
{
public MyViewModel(){}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
public ICommand MyCommand ...
}
This works great!
Now, typically with MVP I'd have my Presenter
hold a reference to the Model
via constructor injection, and raise events on the Model
from the Presenter
to update data in the Model
. I tried the same approach with MVVM, but this requires the ViewModel
to take the Model
as a dependency in its constructor, which seems to make things a little messy with MVVM when using it straight out of the box without some form of IOC (with WPF at least).
So, my two questions are:
- Is injecting the
Model
into theViewModel
the right approach, or should I be implementingINotifyPropertyChanged
interface on theModel
and making use of WPF's binding infrastructure? - To reap the benefits of MVVM, should you almost always implement it with IOC and a DI container, or better still Prism?