Sunday, August 14, 2011

Model-View-ViewModel Pattern


In conventional user interface programming techniques (as we know it from WinForms) we usually add event handlers to controls and implement the logic of a view in the code-behind. It is the most simple and fastest way to get a functional user interface. But this approach has some disadvantages:
  • Presentation and logic are tightly coupled
  • Replacing a control on the view often requires code changes
  • You cannot have more than one view sharing the same logic
  • To test the user interface logic you need to do complex UI testing.

Introducing the Model-View-ViewModel pattern

WPF brings up a very flexible and powerful databinding framework and this favors a new pattern how to bind presentation and logic together.
The idea of the MVVM pattern is the following:
  • model that contains the data
  • A passive view-model that collects and prepares the data so that is can easy be consumed by the view.
  • And a view that is defined in XAML and should not have any logic in the code-behind. It binds to the view-model by only using data binding.

From MVVM in a nutshell--

The VM (ViewModel) is effectively an Observable. It has no idea that the View is observing the state changes that it is broadcasting via the INotifyPropertyChanged interface (basically an interface to define any objects that fire events when their properties change.)

The ViewModel knows about the Model, and is able to retrive and send information back and forth to it through some kind of repository interface. Remember that when the viewmodel is retrieving information, it is updating it's own properties and firing events for the View to observe. This is why databinding in WPF is so amazing and easy (compared to and Winforms at least!)

What this pattern also buys us, is the ability to test the ViewModel in isolation, without having the View in the way (we don't have to fire up our application just to test it, we can pretend like our test suite is basically a user interacting with the View and "Poking" the ViewModel.)

Related Posts Plugin for WordPress, Blogger...