XAMARIN FORMS: MVVM

FAIR WARNING: This article gives an extensive and detailed explanation of MVVM with Xamarin. Feel free to skip directly to sections of interest using the Jump List.

Already an adept of Xamarin and MVVM? Check out my source code directly – GitHub Link

This tutorial assumes you have a basic knowledge of C# as well as Xamarin. Also, some practice in designing your UI using XAML and Xamarin Forms wouldn’t hurt.

 

  1. Introduction

  2. Step 1: Project Structure

  3. Step 2: View [UI]

  4. Step 3: Model

  5. Step 4: ViewModel [Logic]

  6. Step 5: Binding Context

  7. Step 6: Data Binding

  8. Step 7: Introducing ICommands

  9. Step 8: Binding Commands

  10. Step 9: INotifyPropertyChanged

 


MODEL-VIEW-VIEWMODEL [MVVM]

Without MVVM

First off, MVVM is a PATTERN. What’s that you say?

The way I like to put it – Patterns (and Practices) are blessings from our annoyed forefathers who spent much time facing the same problems over and over. One may think of them as half-baked recipes – or simply a particular “way of coding” – that helps avoid those same problems.

For the case of MVVM, it’s a pattern that allows the separation (or as we developers call it: decoupling) of the UI part of an application from its business logic (a.k.a. the functions and processing part).

For instance, a typical Windows Phone application usually has a UI.XAML file for the GUI and an accompanying UI.XAML.CS holding the business logic bound to it.

However, once the MVVM pattern is applied, the architecture is broken into three components:

  1. MODEL: An Object-Oriented Class used to replicate any connected database.

  2. VIEW: The GUI of the application.

  3. VIEWMODEL: Where the majority of the business logic goes.

With MVVM

TYPICAL MODEL-VIEW-VIEWMODEL ARCHITECTURE

MVVM in itself has many implications and several advantages – but that’s not our focus today. Want to know more about MVVM? Just leave a comment and I’ll be sure to post something dedicated to it. Plus you can always research it on your own.

 

XAMARIN WITH MVVM

Time to get coding! Fire up your Visual Studio and Create a new Xamarin Forms (Portable) project named “XDemo” to begin with. All the files and coding will be in the PORTABLE project for this tutorial. We won’t be touching the Platform-specific projects.

For this tutorial, we will be creating a simple BMI Calculator.

 


PROJECT STRUCTURE
MVVM Folder Structure

The first thing to note about an MVVM-based project is its particular folder structure.

STEP 1: Add 3 new Folders

  • Models
  • Views
  • ViewModels

As described ABOVE, each of these folders represent the MVVM Pattern directly.

 


THE VIEW

STEP 2: Create your GUI (BMIView.xaml) in the VIEWS folder.


 


THE MODEL

Ideally, most applications interact with objects usually based on records in a database. So, in that context, our application shall make use of its own BMI class to store some information.

 

STEP 3: Create your BMI Model (Human.cs) in the MODELS folder.


 


THE VIEWMODEL

And here comes the fun part.

The ViewModel is what links your View with your Models. It basically performs all the operations and processing involved. Every bit of information being read from the View (Entry fields) or being written to the View, go through the ViewModel.

Hence, it is only logical that every Input and Output fields in the View must have a corresponding component (or variable) in the ViewModel. Let’s defined those!

 

STEP 4: Create your ViewModel (BMIViewModel.cs) in the VIEWMODELS folder.


 


BINDING CONTEXT

Awesome. We have a View and we have a corresponding ViewModel.

What’s missing? Our View and ViewModel are two completely separate files/components in the project. We did not provide any indication that these need to be linked!

What’s missing is a BINDING CONTEXT. It’s what tells the UI or View that it needs to link up with the ViewModel. There are two ways to do that – via the XAML code or the XAML.CS class. For this tutorial, we’ll go with the XAML.CS method.

 

STEP 5: Set Binding Context in the BMIVIEW.XAML.CS file.


 


DATA BINDING

So now we have a View bound to a ViewModel but something is still missing. We need to specify which components (ENTRY BOXES, LABELS ETC) in the View should bind to which VARIABLES in the ViewModel.

 

STEP 6: Set Data Binding in your BMIVIEW.XAML.


 


INTRODUCING ICOMMANDS

Whoop. Whoop. Things are moving. The only thing left is the Button and luckily MVVM allows you to treat Buttons just like Entry Fields and Labels – with Bindings. For that, we’ll make use of a new type of property: ICOMMAND.

Put simply, one can set a Function as value of an ICOMMAND property – and hence reading that property will return that Function. This nifty little element allows us to bind a Button to an ICOMMAND property – which will in turn return the function assigned to it.

 

STEP 7: Create an ICommand to calculate BMI in BMIVIEWMODEL.cs

Before going any further, let’s break this code down.

First off, the weird “AWAIT ASYNC() => {…}” part of the code is actually called a Lambda Expression. It’s basically defining a function – but without giving it any name (also known as an Anonymous Function)

Next, let’s get one thing out of the way – “ICommand CalculateBMI” is a normal property just like “String Message” or “Double Height”. Except when you read HEIGHT, it returns a value of type DOUBLE. Here CALCULATEBMI returns a value of type COMMAND. And this is the weird part – the COMMAND is actually holding that Lambda Expression or Anonymous Function explained above.

And this Command holding that function is exactly what’s returned when you try to get the value of ICommand CalculateBMI.

Confusing stuff! But read this a few times and follow the logic – and it’ll make sense.

Welcome to programming! You’re a long way from Hello World.

 


BINDING COMMANDS

STEP 8: Bind the Button in BMIVIEW.XAML to the ICommand

Now that you have come to terms with the awesomeness (or weirdness) of ICommands – it’s time to Bind it to that Button. This is done to the “COMMAND” property of the Button in BMIVIEW.XAML


 


INOTIFYPROPERTYCHANGED (WAIT. INOTI-WHAT AGAIN?)

Having completed all the steps above and done all the binding, one would expect this application to run properly. So go ahead and run it – and face that crash and burn like a proper developer. That’s right – nothing changes on clicking the Button.

Here’s the deal. We did everything and bound everything to everything – but one problem remains. We cannot expect the application to just spend all of its resources watching over variables in our ViewModel, waiting for something to change just to show it on the UI. Hence our next step.

 

STEP 9: Implement the INotifyPropertyChanged Interface (INPC)

Implementing INPC will add one line of code to our BMIVIEWMODEL.

The PROPERTYCHANGED variable has two jobs:

Firstly, it acts as an agent between the View and the ViewModel – keeping track of what values are changing. While PROPERTYCHANGED is null – it implies nothing has changed.

Secondly, it updates the View or the ViewModel variables to make sure everything is synced up every time something changes – we just have to call it with the correct parameters.

Following this logic, we now need a function that will call PROPERTYCHANGED with the required arguments each time something changes. This is written as follows:


 

Now we have the PROPERTYCHANGED that will be responsible for updating the View. And we even have a function ONPROPERTYCHANGED that took the job of calling PROPERTYCHANGED with the required arguments when needed.

What’s left? We need to make sure this function is called when something changes!

And typically, a variable changes when you SET a new value to it. Hence each time a value is set to a variable – call ONPROPERTYCHANGED. Simple right? So here we go – time to update the variables we created in BMIVIEWMODEL at the very start of this tutorial.


 

ARE WE DONE YET?

Yep we are. Your application should run just fine now. Go ahead – give it a spin.

Note that the source code on GitHub contains some extra codes on how to use Models to implement a ListView and even a small implementation of Xamarin.Forms MasterDetailPage.

Do not be alarmed. These are things to be covered soon enough – but do give the codes a look.

 

UPDATES

Check out some follow-up articles on Xamarin/Xamarin Forms.

XAMARIN FORMS: OBSERVABLE COLLECTIONS

 

And I guess that is a wrap for today.

Be sure to leave a comment if anything is missing (or just drop in a feedback).

2 Comments

Leave a Reply