//
Home Blog Tech Xamarin Forms. How to Use MVVM Light Framework in Mobile Apps?

Xamarin Forms. How to Use MVVM Light Framework in Mobile Apps?

Popularity of Xamarin technology keeps on growing, especially after purchasing platform by Microsoft.

Idea of “Write once, deploy anywhere mobile” is attractive not only to big corporations, which develop huge business applications, but also to startup world. 

Start-ups are fascinated by possibility of rapid prototyping and implementing changes without need of coordination between few mobile teams.

Create for multiple devices with a shared codebase

To develop an app for Android and iOS, it’s enough to know one programming language: C#.

I’ll give you advice, how to create mobile app quickly by using popular MVVM Light framework, known in .NET environment for its simplicity and testing with ease.

To start work, you will need Apple computer, with Xamarin Studio or Windows PC with Visual Studio environment and libraries, which you can download from Xamarin website.

You can find whole code from this tutorial on my GitHub. Let’s start by creating new project. Choose Xamarin.Forms App to share 99% app code – it’s perfect for start!

Beginning

After creating it, you will see three projects – .Droid, .IOS and shared package, in which we’ll be creating most of our code. IOS and Droid projects contain code specific for platform. It’s a place, where we’ll adapt app interface to system standards – because we want final user to be delighted by graphic layout.

Our goal is to create TODO app, which will display our tasks to do. We’ll start by adding basic dependencies Click Package directory by choosing Add Package option. Select MvvmLight and MvvmLightLibs from NuGet projects. ViewModel directory has been created automatically.

We can start developing add by creating view: choosing menu New > Forms > Forms ContentPage Xaml will create view class with connected/related XAML interface declaration, known from WPF.

TODO app

Our goal is to create TODO app, which will display our tasks to do list. We’ll start by adding basic dependencies Click Package directory by choosing Add Package option. Select MvvmLight and MvvmLightLibs from NuGet projects. ViewModel directory has been created automatically. We can start developing by creating view: choosing menu New > Forms > ContentPage.xaml will create view class with related XAML user interface declaration, known from WPF.

<?xml version="1.0"encoding="UTF-8"?> 
<ContentPagexmlns="http://xamarin.com/schemas/2014/forms"xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"x:Class="MvvmLightStart.ListPage"> 
    <ContentPage.Content> 
    <StackLayoutOrientation="Vertical"HorizontalOptions="FillAndExpand"VerticalOptions="FillAndExpand"Spacing="8"Padding="8"> 
        <StackLayoutOrientation="Horizontal"VerticalOptions="Start"HorizontalOptions="FillAndExpand"> 
            <Entry HorizontalOptions="FillAndExpand"HeightRequest="48"Text="{Binding NewItem}"></Entry> 
            <Button Text="Add"HeightRequest="48"HorizontalOptions="End"Command="{Binding AddItem}"></Button> 
        </StackLayout> 
        <ListViewItemsSource="{Binding Items}"HorizontalOptions="FillAndExpand"VerticalOptions="FillAndExpand"> 
            <ListView.ItemTemplate> 
                <DataTemplate> 
                    <SwitchCellText="{Binding Name}"On="{Binding Done}"  > 
                        <Button Text="Remove"VerticalOptions="CenterAndExpand"/> 
                    </SwitchCell> 
                </DataTemplate> 
            </ListView.ItemTemplate> 
        </ListView> 
    </StackLayout> 
    </ContentPage.Content> 
</ContentPage> 

Lets prepare our model:

using System;
using System.ComponentModel;

namespace MvvmLightStart
{
    public class TodoItem 
    {
        public TodoItem ()
        {
        }

        public String Name 
        {
            get;
            set;
        }

        public bool Done 
        {
            get;
            set;
       }
    
}

Now we have to create our exemplary ViewModel.

using System;
using GalaSoft.MvvmLight;
using System.Collections.ObjectModel;
using GalaSoft.MvvmLight.Command;

namespace MvvmLightStart
{
    public class ListViewModel : ViewModelBase
    {
        public ListViewModel ()
        {
            NewItem = "";
            Items = new ObservableCollection() {
                new TodoItem(){
                    Name="Fix some bug",
                },

                new TodoItem(){
                    Name = "Deploy App"
                },

                new TodoItem(){
                    Name ="Make millions of dollars"
                }
            };
        }

        public String NewItem {
            get;
            set;
        }

        public ObservableCollectionItems {
            get ;
            set ; 
        }

        public RelayCommand AddItem {
            get {
                return _addItem ?? (_addItem = new RelayCommand (() => AddNewItem ()));
            }
        }

        private RelayCommand _addItem;

        private void AddNewItem()
        {
            if (NewItem.Trim().Length > 0) {
                
                Items.Add (new TodoItem (){ Name = NewItem });
                NewItem = "";
                RaisePropertyChanged ("NewItem");
            }
        }

        private ObservableCollection _items;
    }
}

And to modify ViewModelLocator object.

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Ioc;
using Microsoft.Practices.ServiceLocation;

namespace MvvmLightStart.ViewModel
{
    public class ViewModelLocator
    {
        public ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
            SimpleIoc.Default.Register ();
        }

        public ListViewModel Main
        {
            get
            {
                return ServiceLocator.Current.GetInstance();
            }
        }
        
        public static void Cleanup()
        {
        }
    }
} 

To match all elements together, let’s modify starting code.

using Xamarin.Forms;
using MvvmLightStart.ViewModel;

namespace MvvmLightStart
{
    public class App : Application
    {
        public App ()
        {
            // The root page of your application
            MainPage = new NavigationPage(new ListPage());
        }

        private static readonly ViewModelLocator _locator = new ViewModelLocator();
        public static ViewModelLocator Locator
        {
            get    {    return _locator;    }
        }

        protected override void OnStart ()
        {
            // Handle when your app starts
        }

        protected override void OnSleep ()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume ()
        {
            // Handle when your app resumes
        }
    }
}

Now we can start our App by clicking on “Set as Start Project” on Droid or IOS project. System will run device simulator. App uses Binding mechanism – data shared by ViewModel is being displayed by view.

In our solution, ViewModel doesn’t know about view, doesn’t have complicated dependencies and testing is very easy. We receive information about user actions thanks to Command interface.

Spread the word ...

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn
Software Engineer specialised in Mobile Applications development. Focused on code quality and standards, experienced working in fast paced, product-oriented environment – Silicon Valley startups. Co-founder of Mobile Bialystok – local mobile technology enthusiasts group. Also an amateur squash player.