Xamarin Guide 9: Use MVVM Pattern

Scope

This Xamarin Workshop Guide was created for the The Portuguese National Meeting of IT Students (ENEI) by Sara Silva and the original content is available here. To extend it to the global community, it was published in a new project called Xam Community Workshop and the main goal is for any developer, or user group to customize it for their events.

Before reading this article you must read:

Guide 9. Use MVVM Pattern

In this step you will learn how refactor your code to use the MVVM pattern.

“The Model-View-ViewModel (MVVM) pattern helps you to cleanly separate the business and presentation logic of your application from its User Interface (UI). Maintaining a clean separation between application logic and UI helps to address numerous development and design issues and can make your application much easier to test, maintain and evolve. It can also greatly improve code re-use opportunities and allows developers and UI designers to more easily collaborate when developing their respective parts of the application.”
- From the MSDN.

To help understand the MVVM pattern, here is a diagram that explains how it works:



Figure 1: MVVM Pattern diagram

In the Sessions App, you can create two view models, one for each page. To help matching views and view models, in general you should have:

  • SessionsView will be connected with SessionViewModel
  • SessionDetailsView will be connected with SessionDetailsViewModel

Usually all view models are defined in “ViewModels” folders. Then any developer can recognize that the application uses the MVVM pattern and it is easy to match Views and ViewModels. (Any developer however is free to organize the application based on application requirements!).

Let's create the view models!

In the ENEI.SessionsApp project, create a folder called “ViewModels” and then create the class “SessionViewModel”. The result should be something as in the following:

Figure 2: The view model folder

Now you need to refactor the code in SessionView.xaml.cs. For it let's define the SessionViewModel class as in the following:

  1. public class SessionViewModel  
  2. {  
  3.     public SessionViewModel()  
  4.     {  
  5.         Sessions = new ObservableCollection<Session>();   
  6.     }  
  7.   
  8.     public ObservableCollection<Session> Sessions { getset; }  
  9.   
  10.     public async Task LoadDataAsync()  
  11.     {  
  12.        await Task.Run(() =>  
  13.         {  
  14.             if (Sessions.Count == 0)  
  15.             {  
  16.                 var sessions = SessionsDataSource.GetSessions();  
  17.                 foreach (var session in sessions)  
  18.                 {  
  19.                     Sessions.Add(session);  
  20.                 }  
  21.             }  
  22.         });  
  23.     }  
  24. }  
This way, you defined the Sessions list and the LoadDataAsync in the ViewModel, now you need to create the command for each option in the menu.

In the SessionsView.xaml.cs you have the event's handler from the Tap event (for Like, Favorite, Share and SessionDetails) that are defined in XAML as in the following:

  1. <Image.GestureRecognizers>  
  2.   <TapGestureRecognizer x:Name="DetailsGesture"  CommandParameter="{Binding}" Tapped="DetailsGesture_OnTapped" />  
  3. </Image.GestureRecognizers>  
These event's handles are not friendly for implementing the MVVM pattern, to solve it create the “ICommand” that allows the calling of the associated action. This way we need to define the ICommand for each option as in the following:
  1. public ICommand LikeCommand { getprivate set; }  
  2. public ICommand FavoriteCommand { getprivate set; }  
  3. public ICommand ShareCommand { getprivate set; }  
  4. public ICommand SessionDetailsCommand { getprivate set; }  
And in the constructor we must initialize each one, as in the following:
  1. public SessionViewModel()  
  2. {  
  3.     Sessions = new ObservableCollection<Session>();  
  4.     LikeCommand = new Command(ApplyLike);  
  5.     FavoriteCommand = new Command(ApplyFavorite);  
  6.     ShareCommand = new Command(Share);  
  7.     SessionDetailsCommand = new Command(SeeSessionDetails);  
  8. }  
Where each method above is defined by:
  • ApplyLike
    1. private void ApplyLike(object param)  
    2. {  
    3.     var session = param as Session;  
    4.     if (session != null)  
    5.     {  
    6.         session.NumLikes++;  
    7.     }  
    8. }  
  • ApplyFavorite
    1. private void ApplyFavorite(object param)  
    2. {  
    3.     var session = param as Session;  
    4.     if (session != null)  
    5.     {  
    6.         session.IsFavorite = !session.IsFavorite;  
    7.     }  
    8. }  
  • Share
    1. private void Share(object param)  
    2. {  
    3.     var session = param as Session;  
    4.     if (session != null)  
    5.     {  
    6.         var shareService = DependencyService.Get<IShareService>();  
    7.         if (shareService != null)  
    8.         {  
    9.             var status = string.Format("Não percas a sessão {0} de {1}.", session.Name, session.Speaker.Name);  
    10.             shareService.ShareLink("ENEI 2015", status, "https://enei.pt/");  
    11.         }  
    12.     }  
    13. }  
  • SeeSessionDetails
    1. private void SeeSessionDetails(object param)  
    2. {  
    3.     var session = param as Session;  
    4.     if (session != null)  
    5.     {  
    6.         MessagingCenter.Send(session, "SeeSessionDetails");  
    7.     }  
    8. }  

The MessagingCenter is a class that can send and receive messages. In this case, when a user wants to see the session details the view model will send a message with the session to the view and then the view will navigate to the SessionDetailsView.

See more about “Publish and Subscribe with MessagingCenter”.

At the end your SessionViewModel class should be defined as in the following:

  1. public class SessionViewModel   
  2. {  
  3.     public SessionViewModel()   
  4.     {  
  5.         Sessions = new ObservableCollection < Session > ();  
  6.         LikeCommand = new Command(ApplyLike);  
  7.         FavoriteCommand = new Command(ApplyFavorite);  
  8.         ShareCommand = new Command(Share);  
  9.         SessionDetailsCommand = new Command(SeeSessionDetails);  
  10.     }  
  11.   
  12.     public ObservableCollection < Session > Sessions {get;set;}  
  13.     public ICommand LikeCommand {get;private set;}  
  14.     public ICommand FavoriteCommand {get;private set;}  
  15.     public ICommand ShareCommand {get;private set;}  
  16.     public ICommand SessionDetailsCommand { get;private set;}  
  17.   
  18.     private void ApplyLike(object param)   
  19.     {  
  20.         var session = param as Session;  
  21.         if (session != null)   
  22.         {  
  23.             session.NumLikes++;  
  24.         }  
  25.     }  
  26.   
  27.     private void ApplyFavorite(object param)   
  28.     {  
  29.         var session = param as Session;  
  30.         if (session != null)   
  31.         {  
  32.             session.IsFavorite = !session.IsFavorite;  
  33.         }  
  34.     }  
  35.   
  36.     private void Share(object param)   
  37.     {  
  38.         var session = param as Session;  
  39.         if (session != null)  
  40.         {  
  41.             var shareService = DependencyService.Get < IShareService > ();  
  42.             if (shareService != null)   
  43.             {  
  44.                 var status = string.Format("Não percas a sessão {0} de {1}.", session.Name, session.Speaker.Name);  
  45.                 shareService.ShareLink("ENEI 2015", status, "https://enei.pt/");  
  46.             }  
  47.         }  
  48.     }  
  49.   
  50.     private void SeeSessionDetails(object param)   
  51.     {  
  52.         var session = param as Session;  
  53.         if (session != null)   
  54.         {  
  55.             MessagingCenter.Send(session, "SeeSessionDetails");  
  56.         }  
  57.     }  
  58.   
  59.     public async Task LoadDataAsync()   
  60.     {  
  61.         await Task.Run(() = >   
  62.         {  
  63.             if (Sessions.Count == 0)   
  64.             {  
  65.                 var sessions = SessionsDataSource.GetSessions();  
  66.                 foreach(var session in sessions)  
  67.                 {  
  68.                     Sessions.Add(session);  
  69.                 }  
  70.             }  
  71.         }  
  72.     }  
  73. }  
And the SessionsView.xaml.cs should be changed to:
  1. public partial class SessionsView: ContentPage  
  2. {  
  3.     public SessionsView()   
  4.     {  
  5.         InitializeComponent();  
  6.         MessagingCenter.Subscribe < Session > (this"SeeSessionDetails", session = > {  
  7.             Navigation.PushAsync(new SessionDetailsView(session), true);  
  8.         });  
  9.     }  
  10.   
  11.     protected override async void OnAppearing()   
  12.     {  
  13.         base.OnAppearing();  
  14.         var viewmodel = BindingContext as SessionViewModel;  
  15.         if (viewmodel != null)   
  16.         {  
  17.             await viewmodel.LoadDataAsync();  
  18.         }  
  19.     }  
  20.   
  21.     private void SessionsList_OnItemSelected(object sender, SelectedItemChangedEventArgs e)   
  22.     {  
  23.         //workarround to clean the select item  
  24.         if (SessionsList.SelectedItem == null)   
  25.         {  
  26.             return;  
  27.         }  
  28.         SessionsList.SelectedItem = null;  
  29.     }  
  30. }  

The event's handler SessionsList_OnItemSelected will not be changed, because it is a workaround to clean the selected item.

In the SessionsView.xaml we must make a few changes as in the following.

  • Define the SessionViewModel as a resource from the page
    1. <ContentPage.Resources>  
    2.    <ResourceDictionary>  
    3.       <viewModels:SessionViewModel x:Key="SessionViewModel"/>  
  • Binding the SessionViewModel to the BindingContext from the view
    1. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"    
    2.      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"    
    3.      xmlns:converters="clr-namespace:ENEI.SessionsApp.Converters;assembly=ENEI.SessionsApp"    
    4.      xmlns:viewModels="clr-namespace:ENEI.SessionsApp.ViewModels;assembly=ENEI.SessionsApp"    
    5.      x:Class="ENEI.SessionsApp.Views.SessionsView"    
    6.      Title="1010 ENEI || Sessões"    
    7.      BackgroundColor="White"     
    8.      x:Name="ContentPage"     
    9.      BindingContext="{StaticResource SessionViewModel}"    
    10.      Icon="ic_action_users.png">   
  • For each option change the TapGestureRecognizer
    1. <TapGestureRecognizer CommandParameter="{Binding}" Command="{Binding SessionDetailsCommand, Source={StaticResource SessionViewModel}}"/>  

The Command is bound to the respective command from the view model, but each developer should be aware that when the view is loaded, the binding context from the Image is defined with a Session from the respective listview's item. For this reason we must define the binding's Source that uses the view model as a static resource. (At this moment it is not possible to apply relative binding and it is not a good practice to define the commands in the model object because it belongs to the view model!)

If you run the application it must behave as before.

It is possible to define the view model to the SessionDetailsView, but because it only shows a Session and does not have any other capability it is not important to change it.

To learn more about this subject it is recommend to read the following articles.

XAML Basics Contents

Up Next
    Ebook Download
    View all
    Learn
    View all