Introduction to the Model-View-ViewModel Pattern – Part 2

Anand Raja / Tuesday, March 6, 2012

 

Note:

This post is a continuation of Introduction to the Model-View-ViewModel Pattern – Part 1

 

Adding Commanding to our Demo Application

We are now going to take a closer look at the mechanisms used to load and save customer information.  Currently, to accomplish this functionality, we are invoking methods from the View Model via button click events in the View. 

image

 

image

 

 

image

 

We will now remove this code from the button click events and use Commanding to accomplish the same functionality.  In simple terms, a command is an encapsulation of functionality (such as the GetCustomers method).  One of the main benefits of using commanding versus invocation in click events is that it is more conducive for unit testing.  

We are going to create a command class that encapsulates the GetCustomers functionality.   To do this, we simply create a class that implements ICommand

image

 

This class will be used by the View via Command Binding.  The UI buttons will be bound to a respective command that will encapsulate the necessary functionality.  The command will “tell” it’s consumer (View) that it is available to Execute via the “CanExecute” property.  And, it will execute the functionality that it encapsulates when the Execute method is called.  It’s that simple.

This command will be associated with the Load Customers button via the button’s “Command” property:

image

 

 

We will follow the same pattern for the Save functionality.  The commands can be found in the Part 2 source code at the following location:

image

 

We have the option of passing a parameter to the command.  We did not use this option because it was not required.  If required, the parameter can be specified in the XAML.

 

Summary

We have wrapped up our demo by adding Commanding.  With Commanding in place, the code has been removed from the View’s Code Behind class.  Our application is now easier to unit test because we need not test the View to test the Load and Save functionality.  Please note that the Commanding pattern lends itself well to the MVVM pattern, but it is not actually part of it.

MVVM Demo -Part 2.zip