Xamarin

MVVM

Mobile

2016-06-24

Article

Xamarin Forms MVVM

Introduction to the MVVM Pattern in Xamarin covering the project structure, data binding and changes to property values.

Update: This is applicable for .NET MAUI as well.

This tutorial requires a basic knowledge of C# and Xamarin. Some practice in UI design using XAML and Xamarin Forms is also recommended.

MVVM: Model-View-ViewModel

MVVM is a pattern. What’s that, you say?

Patterns (and practices) are blessings from our annoyed forefathers who spent too much time facing the same problems over and over. You can think of them as half-baked recipes that you need to throw your own ingredients in to complete.

Patterns provide you with a “way of coding” to avoid common problems regarding complexity.

For the case of MVVM, it is a pattern that allows for the separation of the user interface of your application from the business logic.

UI: The code that make pretty screens and buttons
Business Logic: The code that makes the buttons actually do something

Without any kind of separation like MVVM, a typical Xamarin application would have a UI.xaml file for the GUI and an accompanying UI.xaml.cs file holding the logic that will run when a user interacts with the UI.

Structure of the Pattern

With the application of MVVM, the project structure is broken into three areas:

  • Models: A class used to represent data
  • Views: The GUI of an application
  • ViewModel: The business logic that runs when an action is taken

Let’s Code

Fire up Visual Studio and create a new Xamarin Forms (Portable) project to begin with.
Our goal is to create a simple BMI calculator.

All the files and codes will be in the portable shared project for this tutorial

Project Structure

Create three new folders as follows:

  • /Models
  • /Views
  • /ViewModels

This directly correlates to the MVVM pattern.

Model

Create a class in the /Models folder.

This model represents the data required when calculating a BMI. Depending on your application, such classes sometimes can represent your database models directly. {{< highlight js >}} public class Human { public string Name { get; set; } public double Weight { get; set; } public double Height { get; set; } public double BMI { get; set; }

public Human(string name, double weight, double height)
{
    Weight = weight;
    Height = height;
    Name = name;
    BMI = weight / (height * height);
}

} {{< /highlight >}}

View

Create a Content Page in the /Views folder. {{< highlight xml >}}

{{< /highlight >}}

ViewModel

Create a class in the /ViewModels folder.

The view-model is responsible for populating the view with data from the model. It also contains the logic behind operations triggered from the view. Logically, every input and output field in the view would need a corresponding element (variable) in the view-model.

{{< highlight js >}} public class BMIViewModel { //FOR THE WEIGHT ENTRY private double _weight; public double Weight { get { return _weight; } set { _weight = value; } }

//FOR THE HEIGHT ENTRY
private double _height;
public double Height
{
    get { return _height; }
    set { _height = value; }
}

//FOR THE NAME ENTRY
private string _name;
public string Name
{
    get { return _name; }
    set { _name = value }
}

//FOR THE MESSAGE DISPLAY
private string _message;
public string Message
{
    get { return _message; }
    set { _message = value; }
}

public BMIViewModel()
{
    //INITIALIZING UI AND VARIABLES
    Message = "HELLO XAMARIN FROM MVVM!";
}

} {{< /highlight >}}

Bindings

At the moment, the view and view-model are completely separate files in the project. The view and the elements in the view need to be informed of the existence of the view-model (or vice-versa) to connect the two.

Binding Context

First and foremost, we need a binding context, which essentially tells the view that it needs to link up to its view-model. This can be done directly in xaml file, or via the xaml.cs (code-behind) file.

We will go for xaml.cs in this tutorial.

{{< highlight js >}} public partial class BMIView : ContentPage { public BMIView() { InitializeComponent(); this.BindingContext = new BMIViewModel(); } } {{< /highlight >}}

Data Binding

The view is now bound to the view-model, but something is still missing. Similar to the binding context, the view components (Entry Boxes, Labels etc.) also need to bind themselves to the variables in the view-model.

Let’s set up the data-binding in the view.

{{< highlight xml >}}

Recently posted articles