Search

Monday, April 8, 2013

Demystifying MVVM (Model View View-Model)

If are new to programming or haven’t used modern design and development patterns, MVVM could be a confusing acronym that makes no sense to you.  If you are familiar with legacy design patterns (like MVC and MVP), the model view view-model may look a bit weird, although you’ll find it to be an excellent evolution to your current programming paradigm. 

In layman’s terms the three areas are broken down with these definitions:
  1. Model – The data, typically coming from a database, web service, file, or other source
  2. View – The graphic user interface, such as a windows form or web screen
  3. View Model – An abstraction layer that manipulates the data (model) so the screen (view) can display it.  The view model will include other actions (methods/functions) that can save, edit and persist data.

The real power behind MVVM is the view model.  The view model has OnPropertyChanged events that notify the listeners that data has changed and you should refresh your UI.  Most view models are based upon a ViewModelBase class that has event handlers that are subscribed to and other methods that manage the low level state of the view model.  I included a code snippet at the end of the article that I used in all my projects.

The view model is so powerful, you can reach the point where you have no code behind your view.  You can have the view code (HTML, XAML, etc.), your view model (which can handle button click events, data bindings and data events like inserts, updates and selects) and your model.  You can build test driven software that validates your assumptions and requirements without having a working application.

You can serve up mobile applications, web and thick client from the same infrastructure.  The end result can be limitless.  You can support iPhones, Android, Ubuntu, UNIX and Windows clients.  Your development time can be dramatically reduced and your quality can be increased as well. 

The best part there’s so many different programming technologies that support it.  WPF and Silverlight inherently support it.  JavaScript has a library known as Knockout that implements MVVM.  You can leverage the Razor engine, standard ASP.NET, Ruby and so much more. 

Look at MVVM and you’ll find a new paradigm in programming that’s easy, powerful and efficient.  The best part, it’s light and doesn’t require a lot of infrastructure to make it work. 


public class ViewModelBase : INotifyPropertyChanged
{
/// <summary>
/// Set the ViewModelBase to throw exceptions when property names are invalid
/// </summary>
private bool throwOnInvalidPropertyName = true;

/// <summary>
/// Expose a property to override the base value
/// </summary>
protected bool ThrowOnInvalidPropertyName
       {
              get
              {
                     return throwOnInvalidPropertyName;
}
set
              {
                     throwOnInvalidPropertyName = value;
}
}
/// <summary>
/// Setup an event to handle property changes
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Verifies if the property is valid and raises an event that its changed
/// </summary>
/// <param name="propertyName">Property that's changed</param>
protected virtual void OnPropertyChanged(string propertyName)
{
            VerifyPropertyName(propertyName);
 
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);
       handler(this, e);
}
}
 
/// <summary>
/// Verify that the property name matches a real, public, instance property on this object
/// </summary>
/// <param name="propertyName">Property to check</param>
[Conditional("DEBUG")]
[DebuggerStepThrough]
public void VerifyPropertyName(string propertyName)
{
            if (TypeDescriptor.GetProperties(this)[propertyName] == null)
           {
                       string message = "Invalid property name: " + propertyName;
if (ThrowOnInvalidPropertyName)
throw new Exception(message);
else
Debug.Fail(message);
}
       }
}

No comments:

Post a Comment