Thursday, May 10, 2012

Silverlight 4.0 and MVVM Pattern

What is MVVM Pattern?


MVVM (Model-View-View Model) is the  design Pattern code model used for WPF/Silverlight UI. MVVM is the guideline a developer should follows in order to achieve a more testable, debug gable, manageable, readable Application.

MVVM is implemented with zero code behind.  Yes, no button click event hander in the code behind file, no form/windows load logic, no UI binding logic, and no UI validation or type casting code in the code behind file. Yes, I mean absolutely no code or logic in the UI mainpage.xaml.cs file.

The reason we don't want to put code-behind in our project is so that one can write a unit test against the code and create instances and run methods on our instances in a unit test.

The following features are used in order to achieve the MVVM pattern with no logic on the UI code behind file and to make sure that the presentation layer and logic remain loosely couple.
  1. Using the strong two-way binding capability of the WPF/Silverlight UI (through XAML)
  2. Implementing an IValueConvert for binding (eg: string converted to a Color instance, and also avoid type casting)
  3. Use INotification in our model or Dependency Property
  4. Set the data context at the xaml level
  5. Set Static resources at the xaml level
  6. ICommand for avoiding the code behind event handler.
  7. Use of validation=true in xaml(presentation layer)
Before MVVM, the MVP pattern was famous for its use in WinForm and WPF applications (it never took full advantage of the two-way binding feature of WPF).  The MVC pattern is still well-known for its use with Asp.net Application.

Below are some drawbacks of the old fashion WinForm or WPF/Silverlight applications that didn't leverage the power of the mvvm pattern.
  1. The presentation and the code behind logic is tightly coupled
  2. If we change the UI control we are forced to change the logic in the code behind
  3. It makes it hard to imagine a way of having more than one view sharing the same logic.
  4. It's not possible to write a unit test for a view that uses code behind because the presentation layer is tightly couple to the control.
  5. In previous practice with the WPF application, the view (xaml) often acted as a data store.
Advantages of MVVM pattern
  1. Proper layering of the view and the data. The data is not stored in the view, The view is just for presenting the data.
  2. Clean testable and manageable code.
  3. No code behind so the presentation layer and the logic is loosely coupled.
  4. With Silverlight 4.0 we have new ICommand Support (this was previously only present in the PRISM framework

No comments:

Post a Comment