Understanding the MVVM Pattern

*Disclosure: This post may contain affiliate links, meaning, at no cost to you I may get some coffee money if you click through and make a purchase.

I mentioned in a previous post that I had become a Xamarin Certified Mobile Professional (check it out for an introduction too) which I really enjoyed getting to and learned a lot of about Xamarin, .Net, and the platforms involved. I’m going to start sharing more of what what I’ve learned starting now.

For this post as the title suggests we are going to look at the MVVM pattern…

MVVM is a software architecture pattern and is a variation of the MVC (Model-View-Controller Pattern). The acronym stands for Model-View-ViewModel, which identifies the key components within an MVVM targeted app but we’ll get to that.

The pattern is concerned with helping us decouple our business and presentation logic from the user interface.

Why would we want to do this?

By providing that separation between the components we can improve our development by allowing different teams (such as the design team and the development team) to work to an agreed contract and develop their own components independent of each other.

As the name suggests the Model-View-ViewModel pattern has 3 core components, Model, View, and ViewModel. As they say a picture (diagram in this case) paints a thousand words so hopefully the diagram below gives you an idea of the relationship

At a high level the interactions are as follows:
  • View: Knows about the ViewModel
  • ViewModel: Knows about the Model but does not know about the View
  • Model: Does not know about the View or ViewModel

As you can see the ViewModel provides a layer of separation between our View and Model components and through the use of Data Binding we can decouple our ViewModels from our Views. By developing our apps in this way we get quite a few benefits:

  • Adaptive: We can take old Models and adapt them for use in our apps through our ViewModels. e.g. models developed for a web app that aren’t suitable for mobile can be adapted via the ViewModel to provide our Views what they need.
  • Testable: Our unit tests can be developed and maintained easier as our C# code is separate from our UI.
  • Decoupled: We reduce the dependencies between the components and so can update them independent of the others, providing of course we continue to adhere to our contracts.

Now that we have an overall idea of MVVM lets take a look at each component.

View:

The first component we’ll look at is the View. It is responsible for what the user  sees, the structure, layout, and appearance of each Page. Within Xamarin we have two files, a .xaml file and a .xaml.cs file, which together define our views (or pages). As the names suggest our .xaml file will hold our Xaml implementation of the UI and the .xaml.cs file will hold our C# code-behind.

So we can develop our Views using either Xaml or C#, with the use of the MVVM pattern in our apps we aim to do everything in Xaml and have the bare-minimum C#, however in some cases we may need to use C#, such as with animations.

One question you may have now is if we aim to put as little code in our View code-behind how do we allow users to do anything, such as fill in a form and submit it?

For this we have Commands, if a control (an visual item) supports the ICommand interface we can register to it to a property on it’s ViewModel (which must implement this interface). So when a controls ICommand action is triggered the associated property on the ViewModel is triggered. Additionally there are features called Behaviours, these can be attached to an object in the view and wait for either a command to be triggered or an event to be raised. Once the behaviour has been triggered it can then either call the ICommand property or a method in the ViewModel.

ViewModel:

Our ViewModels provide Properties and Commands for our views to attach to through the use of Data Binding and through this relationship it can flow the UI presentation logic to the View without needing to know about the View. This is done through the use of the INotifyPropertyChanged interface which uses the OnPropertyChanged method to notify the View that a change has occurred, making apps very responsive if implemented correctly. 

Think of this relationship as the View is used to define how the functionality will be displayed and the ViewModel, through the use of properties and commands, defines what will be displayed in the UI.

Looking at the diagram above again you can see that our ViewModel sits between our View and our Model, this is no accident. Through the ViewModel we can co-ordinate our Views based on based on our Models and updated our Models based on our Views through the ViewModel, providing that layer of separation between the two components. In some cases the ViewModel will expose the Model directly to the View but we also have the control to perform data modification in the ViewModel to meet the needs of our expected presentation design. A very simple example could be convertign data from one format to another such as from lbs to kgs. 

As I mentioned above we perform the communication between our Views and ViewModels through DataBinding. Data Binding allows us to hook our UI elements to properites in our ViewModel and then provide either one or two way communication between the two components. 

For the ViewModel to View communication to occurr the relevant property must raise the property changed event, called OnPropertyChanged. In order to do this a ViewModel must implement the INotifyPropertyChanged interface and raise the event when a relevant property is changed. By doing this whenever the property is changed the relevant UI element will automatically be passed the new value to display. Providing up to date information to the user.

If you have a list or other collection it is a bit easier to perform that communication, use the data structure ObservableCollection<T> and much of the work is done as it implements the INotifyCollectionChanged interface. All you need to do is hook it up.

Model

Lastly, we have the final component, the ‘Model’. This is quite straightforward, the Model is any class not directly associated with the visual aspect and can be viewed as representing the domain model.

This generally involves our data model and our business and validation logic. Examples of Model level entities are Plain Old CLR Objects (POCOs) but also include Data Transfer Objects (DTOs), entity, and proxy objects.

We primarily use this component with services and repositories for data access and caching.

So there we have it an intro to MVVM and the core components. Our View handles the formating of what the user sees, our ViewModel what will be seen, and the Model helps to organise and process.

The pattern is very popular within the mobile development domain and I highly recommend you give it a go if you haven’t already to see if you could benefit from it.

Keep and eye out for the next post.

Leave a Reply

Your email address will not be published. Required fields are marked *