MVVM UnPlugged

In Part 1 of the MVVM series “MVVM Unplugged – Definition, Benefits, Classes and its interactions“, we saw that the MVVM pattern provides a clean separation between your application’s user interface, its presentation logic, and its business logic and data by separating each into separate classes. In this blog, we are going to focus on the Data Binding aspect of implementing the MVVM pattern esp. Databinding of properties using INotifyPropertyChanged interface.

Data Binding

Data binding is one of the very important mechanism through which the various classes under the MVVM pattern interact with each other.WPF and Silverlight both provide powerful data binding capabilities. Silverlight and WPF data binding supports multiple data binding modes. There are various modes of data binding, with one-way data binding, UI controls can be bound to a view model so that they reflect the value of the underlying data when the display is rendered. Two-way data binding will also automatically update the underlying data when the user modifies it in the UI. To achieve data binding and to make ensure that the UI is kept up to date when the data changes in the view model, it should implement the appropriate change notification interfaces.  If there are properties in the ViewModel that needs to be data bound with the view then the view model should implement the INotifyPropertyChanged interface. If the view model represents a collection, it should implement the INotifyCollectionChanged interface or derive from the ObservableCollection class that provides an implementation of this interface. The INotifyPropertyChanged interface and INotifyCollectionChanged interface both define an event that is raised whenever the underlying data is changed. Any data bound controls will be automatically updated when these events are raised. WPF and Silverlight data binding supports binding to nested properties via the Path property. Thumb rule for achieving data binding in WPF or Silverlight is that any view model or model that is accessible to the view should implement either the INotifyPropertyChanged or INotifyCollectionChanged interfaces, as per the need.

In this blog, we are going to focus on the implementation of the INotifyPropertyChanged interface. If we look in the object browser of the INotifyPropertyChanged, we see that it’s a very simple interface and it is just asking the concrete classes to expose an event which takes in a delegate PropertyChangedEventHandler delegate.

namespace System.ComponentModel
{
       // Summary: Notifies clients that a property value has changed.
       public interface INotifyPropertyChanged
       {
           // Summary: Occurs when a property value changes.
           event PropertyChangedEventHandler PropertyChanged;
       }
}

The PropertyChangedEventHandler is defined as a method that will handle the INotifyPropertyChanged. PropertyChanged event is raised when a property is changed on a component. It takes in two parameters:

  •  sender – The source of the event.
  •  e – A System.ComponentModel.PropertyChangedEventArgs that contains the event data.

If we look into the PropertyChangedEventArgs, it has a constructor which takes in a parameter PropertyName as string now this parameter is basically is the property which has changed.

public PropertyChangedEventArgs(string propertyName);

Now since we have a basic understanding of how the INotifyPropertyChanged interface works and what constitutes the PropertyChangedEventHandler and PropertyChangedEventArgs. Lets take a look at an example of how we are going to implement this interface.

View

In our view, We have created a simple window which is depicting a user and has three properties defined on it – First Name , Last Name and Age. Let’s go ahead and create a view model for our simple view.

ViewModel

 Lets create a view model for our User View and name it as UserViewModel. To implement the databinding, lets implement the INotifyPropertyChanged interface. As seen in the code below, we see that for implementing the INotifyPropertyChanged, we have declared a public event PropertyChanged which takes in a delegate method PropertyChangedEventHandler. Now for all the properties which we want to have databinding capabilities, we have gone ahead and provided the event trigger by calling the delegate PropertyChanged.

class UserViewModel : INotifyPropertyChanged
{
    private int _age;
    private string _firstName;
    private string _lastName;
    public event PropertyChangedEventHandler PropertyChanged;
    public UserViewModel(){}
    public string LastName
    {
       get { return _lastName; }
       set
       {
          if (value != _lastName)
          {
             _lastName = value;
             if (PropertyChanged != null)
             {
               this.PropertyChanged(this, new propertyChangedEventArgs("LastName"));
             }
          }
       }
    }
    public string FirstName
    {
        get { return _firstName; }
        set
        {
           if (value != _firstName)
           {
             _firstName = value;
             if (PropertyChanged != null)
             {
                this.PropertyChanged(this, new PropertyChangedEventArgs("FirstName"));
             }
           }
        }
    }
    public int Age
    {
        get { return _age; }
        set
        {
           if (value != _age)
           {
              _age = value;
              if (PropertyChanged != null)
              {
                 this.PropertyChanged(this, new PropertyChangedEventArgs("Age"));
              }
           }
        }
    }
}

To make this code working, we now just need to define these bindings in the User View XAML code and we also need to provide the hook up code between the view and viewmodel.

<TextBox Height="23" HorizontalAlignment="Left" Margin="242,27,0,0" Name="firstNameTextBox" Text ="{Binding FirstName,Mode=TwoWay}" VerticalAlignment="Top" Width="120" Grid.Column="1" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="242,69,0,0" Name="lastNameTextBox" Text ="{Binding LastName,Mode=TwoWay}" VerticalAlignment="Top" Width="120" Grid.Column="1" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="242,115,0,0" Name="ageTextBox" Text ="{Binding Age,Mode=TwoWay}" VerticalAlignment="Top" Width="120" Grid.Column="1" />

As you can see from the code above, we have bound the textboxes with the Properties defined in our UserViewModel class.

Now as a final step , we just need to hook up the View and Model, one way in which we can do this is by creating an object of View Model in our constructor of the view and then setting up the data context of the view as the view model.

UserViewModel viewModel = new UserViewModel();
this.DataContext = viewModel;

Problems with this implementation of the INotifyPropertyChanged.

If we notice it closely, with the approach described above, we have to implement the INotifyPropertyChanged interface on all of our View Models and this would lead to errors as we have to repetitively specify the property name in the event argument which is an string. Let’s look at a better way of implementing the same thing.

 Better Approach : Using NotificationObject of Prism

The Prism Library provides a convenient base class from which you can derive your view model classes that implements the INotifyPropertyChanged interface in a type-safe manner. The base class it provides us is called NotificationObject. Let’s take a look at its implementation.

public abstract class NotificationObject : INotifyPropertyChanged
{
   protected NotificationObject();
   // Summary: Raised when a property on this object has a new value.
   public event PropertyChangedEventHandler PropertyChanged;
   // Summary: Raises this object's PropertyChanged event.
   // Parameters: 
   // propertyExpression:
   // A Lambda expression representing the property that has a new value.
   // Type parameters:
   // T: The type of the property that has a new value
   protected void RaisePropertyChanged(Expression propertyExpression);
   // Summary: Raises this object's PropertyChanged event for each of the properties.
   // Parameters:
   // propertyNames: The properties that have a new value.
   protected void RaisePropertyChanged(params string[] propertyNames);
   // Summary:
   // Raises this object's PropertyChanged event.
   // Parameters:
   // propertyName: The property that has a new value.
   protected virtual void RaisePropertyChanged(string propertyName);
}

In the code above, we see that Prism has defined a class NotificationObject which implements the INotificationPropertyChanged interface.  We also see that it has three overloaded methods defined for Raising the Property Changed , one method takes, the Lambda expression representing the property that has a new value, the second one takes an array of properties that has a new value and the third one is similar to the one which we explained above in our implementation of the INotifyPropertyChanged event which takes in the property name that has a new value.

 Lets implement a new View Model class for our user view , this one will derive from the NotificationObject provided by the Prism.

class UserBindingUsingPrismViewModel : NotificationObject
{
   private int _age;
   private string _firstName;
   private string _lastName;
   public string LastName
   {
      get { return _lastName; }
      set
      {
         if (value != _lastName)
         {
           _lastName = value;
           RaisePropertyChanged(() => this.LastName);
         }
      }
   }
   public string FirstName
   {
       get { return _firstName; }
       set
       {
          if (value != _firstName)
          {
            _firstName = value;
            RaisePropertyChanged(() => this.FirstName);
          }
       }
   }
   public int Age
   {
      get { return _age; }
      set
      {
         if (value != _age)
         {
           _age = value;
           RaisePropertyChanged(() => this.Age);
         }
      }
   }
}

As we can see from the above code, our inherited view model class is now raising the property change event by invoking RaisePropertyChanged using a lambda expression that refers to the property. Using a lambda expression in this way involves a small performance cost because the lambda expression has to be evaluated for each call. The benefit is that this approach provides compile-time type safety and refactoring support if you rename a property. Although the performance cost is small and would not normally impact your application, the costs can accrue if you have many change notifications. In this case, one should consider using the non-lambda method overload.

MVVM Unplugged – Definition, Benefits, Classes and its interactions

Definition
MVVM is an architectural pattern that facilitates the clear separation of the GUI with the logic. It provides a clean separation between application’s user interface, its presentation logic, and its business logic and data by separating each into separate classes. The MVVM pattern is a close variant of the Presentation Model pattern, optimized to leverage some of the core capabilities of WPF and Silverlight, such as data binding, data templates, commands, and behaviors.  

Benefits
The separation of application logic and UI helps to address numerous development and design issues and can make the application much easier to test, maintain, and evolve. It can also greatly improve code re-use opportunities and allows developers and UI designers to more easily collaborate when developing their respective parts of the application.

Some of the benefits achieved by using MVVM are explained in detail below:

  • Concurrent Development: One of the biggest advantage is that during the development process, developers and designers can work more independently and concurrently on their components. The designers can concentrate on the view, and if they are using Expression Blend, they can easily generate sample data to work with, while the developers can work on the view model and model components.
  • Testability: The developers can create unit tests for the view model and the model without using the view.
  • Easy Redesign of the UI: It is easy to redesign the UI of the application without touching the code because the view is implemented entirely in XAML. A new version of the view can easily be worked upon and plugged into the existing view model.

Details
In the MVVM pattern, the UI of the application and the underlying presentation and business logic is separated into three separate classes: the view, which encapsulates the UI and UI logic; the view model, which encapsulates presentation logic and state; and the model, which encapsulates the application’s business logic and data. The view interacts with the view model through data binding, commands, and change notification events. The view model queries, observes, and coordinates updates to the model, converting, validating, and aggregating data as necessary for display in the view. 
The interaction between the classes is explained in the diagram below:
MVVM Class Interactions
Class Interactions Diagram 

Characteristics of the View Class

  • The view in the MVVM pattern defines the structure and appearance of what one sees on the screen.
  • As a thumb rule, one should not put any logic code that needs to be tested by unit test in the View.
  • The view is a visual element. The view defines the controls contained in the view and their visual layout and styling.
  • The view can customize the data binding behavior between the view and the view model by using the Value converters to format the data or by using the validation rules to provide additional input data validation to the user.
  • The view defines and handles UI visual behavior, such as animations or transitions that may be triggered from a state change in the view model or via the user’s interaction with the UI.

Characteristics of View Model: 

  • The view model is a non-visual class and does not derive from any WPF or Silverlight base class.
  • It encapsulates the presentation logic and is testable independently of the view and the model.
  • The view model does not reference the view. It implements properties and commands to which the view can data bind. It notifies the view of any state changes via change notification events via the INotifyPropertyChanged and INotifyCollectionChanged interfaces.
  • The view model acts as coordinator between the view and the model. It may convert or manipulate data so that it can be easily consumed by the view and may implement additional properties that may not be present on the model.
  • It may also implement data validation via the IDataErrorInfo or INotifyDataErrorInfo interfaces.
  • The view model may define logical states that the view can represent visually to the user.
  • Typically, there is a one-to many-relationship between the view model and the model classes.
  • In most cases, the view model will define commands or actions that can be represented in the UI and that the user can invoke. 

Characteristics of the Model Class 

  • The model in the MVVM pattern encapsulates business logic and data. Business logic is defined as any application logic that is concerned with the retrieval and management of application data and for making sure that any business rules that ensure data consistency and validity are imposed.
  • As a thumb rule models should not contain any use case–specific application logic.
  • Mostly the model represents the client-side domain model for the application. It can define data structures based on the application’s data model and any supporting business and validation logic.
  • The model classes do not directly reference the view or view model classes and have no dependency on how they are implemented.
  • The model classes are typically used in conjunction with a service or repository that encapsulates data access and caching.