Thursday, July 1, 2010

Model-View-ViewModel pattern

Model-View-ViewModel Pattern

Introduction

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:

  • A 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.