Getting Started With Xamarin Forms MVVM Light

Xamarin.Forms is a cross-platform UI toolkit that allows developers to easily create native user interface layouts that can be shared across Android, iOS, and Windows Phone. This a great benefit for .NET(C#) Devs, mainly for Windows Phone and Store App Developers. Let's see some differences  between the Xamarin.Native and Xamarin.Forms approach.

Xamarin

In Xamarin, previously we used to share onlythe  code part with preprocessor directives targeting independent platforms like the following:

 

  1. #if __IOS__  
  2. // iOS-specific code  
  3. #endif  
  4. #if __ANDROID__  
  5. // Android-specific code  
  6. #endif  
  7. #if Windows_App  
  8. var path = filename;  
  9. #else  
UI is Independent to each platform with Xamarin.Forms we can use one code one UI Across all Platforms(UI-Xaml/C#) Codebehind (C#). You can choose XAML or C# to For UI. In my view xaml is easier to go with. Sad thing is there is no designer view for Xamarin forms so every time you have to debug and check, but you can use a third party library like "Gorilla Player." So let's create our first project. In this project we are using MVVM Light to achieve cross-platform functionality.

Make sure you have Visual Studio 2015 Installed with latest update of Xamarin.

Blank app

After creating Project >Right Click Solution>Manage Nuget Packages>search for Xamarin Forms:

Manage Nuget Packages

Make sure you have installed Latest Xamarin Forms and Select Entire Project(Right) >Install. This will update your entire project to the latest Xamarin Forms Version. And after that Install MVVM Light.

MVVM Light

Select Entire Project and Install.

After this Go to Updates Tab in the same window. Update any Packages if Needed.

Remove Views And ViewModel Folder in All Three Platforms Except your(Portbale) Project.

Now Go to your PCL Project(Top).

App.cs

Open App.cs Page.

Remove all Code in App Constructor.

Write it like this:
  1. public class App: Application  
  2. {  
  3.     public App()  
  4.     {  
  5.         MainPage = new NavigationPage(GetMainPage());  
  6.     }  
  7.     private static ViewModelLocator _locator;  
  8.     public static ViewModelLocator Locator  
  9.     {  
  10.         get  
  11.         {  
  12.             return _locator ? ? (_locator = new ViewModelLocator());  
  13.         }  
  14.     }  
  15.     public static Page GetMainPage()  
  16.     {  
  17.         return new MainPage();  
  18.     }  
  19.     protected override void OnStart()  
  20.     {  
  21.         // Handle when your app starts  
  22.     }  
  23.     protected override void OnSleep()  
  24.     {  
  25.         // Handle when your app sleeps  
  26.     }  
  27.     protected override void OnResume()  
  28.     {  
  29.         // Handle when your app resumes  
  30.     }  
  31. }  
By Default You will have ViewModel Folder With One View Models and One ViewModle Locator.

Now Right Click PCL Project And Add New Folder Called "Views". To that Views Folder add Again add Xaml Page.

Xaml Page

Rename it To MainPage. The name you're adding should be identical to your Viewmodel. What MvvmCross will do is, if your ViewModel is "MainViewModel" then it tries to Find A Page MainPage>means it Removes ViewModel and Replace Page and Search For That Page.

So If your ViewModel is FirstViewModel Than your Page name Should Be FirstPage Vise Versa.

Now Your Go To ViewModelLocator. Here you can Specify Your Default ViewModel which you want to start the Project.
  1. public class ViewModelLocator  
  2. {  
  3.     /// <summary>  
  4.     /// Initializes a new instance of the ViewModelLocator class.  
  5.     /// </summary>  
  6.     public ViewModelLocator()  
  7.     {  
  8.         ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);  
  9.         ////if (ViewModelBase.IsInDesignModeStatic)  
  10.         ////{  
  11.         //// // Create design time view services and models  
  12.         //// SimpleIoc.Default.Register<IDataService, DesignDataService>();  
  13.         ////}  
  14.         ////else  
  15.         ////{  
  16.         //// // Create run time view services and models  
  17.         //// SimpleIoc.Default.Register<IDataService, DataService>();  
  18.         ////}  
  19.         SimpleIoc.Default.Register < MainViewModel > ();  
  20.     }  
  21.     public MainViewModel Main  
  22.     {  
  23.         get  
  24.         {  
  25.             return ServiceLocator.Current.GetInstance < MainViewModel > ();  
  26.         }  
  27.     }  
  28.     public static void Cleanup()  
  29.     {  
  30.         // TODO Clear the ViewModels  
  31.     }  
  32. }  
Suppose if you want to start with BaseVieModel. Create a BaseViewModel class. Make sure it inherits public class BaseVieModel: ViewModelBase.

Now in ViewModelLocator Replace MainViewModel With "BaseVieModel". So that Your Page Name Should Be "BasePage.Xaml".

Now le'ts get gack.  So for now we have MainViewModel, ViewModelLocator registered with MainViewModel as a startup ViewModel.

So, by default your ViewModel implants INotifyProperty changed, so it makes sure when there is a change in your collection or properties it notifies the UI.

Namespace

Now to our View MainPage.Xaml just add the following code:
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage  
  3.     xmlns="http://xamarin.com/schemas/2014/forms"  
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  5.       x:Class="XamarinMVVMLight.Views.MainPage">  
  6.     <Button Text="{Binding ClickCountFormatted}"  
  7.       Command="{Binding IncrementCommand}"  
  8.       VerticalOptions="Center" />  
  9. </ContentPage>  
Now go to MainViewModel

Add the following code:
  1. public class MainViewModel: ViewModelBase  
  2. {  
  3.     public  
  4.     const string ClickCountPropertyName = "ClickCount";  
  5.     private int _clickCount;  
  6.     /// <summary>  
  7.     /// Initializes a new instance of the MainViewModel class.  
  8.     /// </summary>  
  9.     public MainViewModel()  
  10.     {}  
  11.     public int ClickCount  
  12.     {  
  13.         get  
  14.         {  
  15.             return _clickCount;  
  16.         }  
  17.         set  
  18.         {  
  19.             if (Set(() => ClickCount, ref _clickCount, value))  
  20.             {  
  21.                 RaisePropertyChanged(() => ClickCountFormatted);  
  22.             }  
  23.         }  
  24.     }  
  25.     public string ClickCountFormatted  
  26.     {  
  27.         get  
  28.         {  
  29.             return string.Format("The button was clicked {0} time(s)", ClickCount);  
  30.         }  
  31.     }  
  32.     private RelayCommand _incrementCommand;  
  33.     /// <summary>  
  34.     /// Gets the IncrementCommand.  
  35.     /// </summary>  
  36.     public RelayCommand IncrementCommand  
  37.     {  
  38.         get  
  39.         {  
  40.             return _incrementCommand ? ? (_incrementCommand = new RelayCommand(  
  41.                 () =>  
  42.                 {  
  43.                     ClickCount++;  
  44.                 }));  
  45.         }  
  46.     }  
  47. }  
So, whenever you tap on the button it will call IncrementCommand and increased count. As our viewModel Implements INotifyProperty Changed Interface, it will bind theUI with Incremented Count Value.

Now go to Android Project, then MainActivity.cs page and make sure the following code is there which calls PCL project at startup and respectively in all platforms.

 

  1. protected override void OnCreate(Bundle bundle)  
  2. {  
  3.     base.OnCreate(bundle);  
  4.     global::Xamarin.Forms.Forms.Init(this, bundle);  
  5.     LoadApplication(new App());  
  6. }  
IOS - AppDelegate.Cs
  1. public override bool FinishedLaunching(UIApplication app, NSDictionary options)  
  2. {  
  3.     global::Xamarin.Forms.Forms.Init();  
  4.     LoadApplication(new App());  
  5.     return base.FinishedLaunching(app, options);  
  6. }  
WindowsPhone - MainPage.Xaml.Cs Page
  1. public MainPage()  
  2. {  
  3.     this.InitializeComponent();  
  4.     LoadApplication(new App());  
  5. }  
If you want to add Windows Phone 8.1 Or Windows 8.1 or UWP App Remove Current windows project and go to PCL project, Properties, then change Target Platform:

Click Change

And then add new Windows 8.1/Windows Phone 8.1/UWP project to the solution and and reference of PCL Project as well as Xamarin Forms Nuget.

Now select your own project as startup and run. Now we successfully created our first Xamarin Forms Project. Please comment below if you have any questions.

Read more articles on Xamarin: