MVVM stands for Model View ViewModel it is a design pattern for UI applications. It has predominantly been used for XAML (eXtensible Application Markup Language) based frameworks such as WPF, Silverlight, UWP, Xamarin and now Avalonia.

In early UI applications the UI logic and the buisness logic of the application were easily mixed. This leads to code that is difficult to test and eventually become difficult to maintain. Making changes to UI code can break the application in other areas.

The MVVM pattern ensures seperation of concerns within a UI application to ensure testability and maintainability.

MVVM is no longer restricted to just .NET and XAML based applications and is starting to be adopted in various guises on other technologies.

MVVM separates the various aspects of the UI application into 3 layers as show below.

The model layer represents buisness logic. This could be communicating with a cloud service, database or even just implementing some kind of algorithm or talking to hardware.

The model can talk to the ViewModel via events. Equally the ViewModel can pass data or call methods in the model layer.

The viewmodel can be thought of as an adaptor that sits between the View (UI) and the buissness logic. It can call methods or listen to events in the model to update its state. The viewmodel can update the UI by raising a special event called INotifyPropertyChanged this event is listened to by the View and when its fired the UI knows to checks for updates in the ViewModel and the update the display.

The View is a presentation layer that describes how to render the data in the ViewModel. It is loosely coupled to the ViewModel. The View uses DataBinding to display properties on the ViewModel and Commands to signal events back to the ViewModel.

Ok so we have learned a few terms here which may not be so clear if this is the first time you have come across them. I feel its best to learn through doing so lets get started with something practical.

In this tutorial we will build a very basic application that demonstrates each of these layers covering the following:

Updating the UI from the ViewModel using DataBinding

Updating the ViewModel from the UI using DataBinding

Calling code in the Model from the ViewModel causing updates in the UI

Events signaling change in the Model to update the ViewModel and as a result the UI

Start by creating a new Avalonia MVVM application and giving it a name of your choosing.