Simplifying MVVM INotifyPropertyChanged On Xamarin.Forms

The goal is simplifying MVVM INotifyPropertyChanged in Xamarin Forms therefore making it unnecessary to keep inheriting base classes and handling the setter of each ViewModel Property.
 
Remember that the code shown here is just an example to demonstrate an alternative to the normal methods with MVVM. Nowadays frameworks exist to work with MVVM in Xamarin Forms, the Prism is one of them. 
 
What do we need?
  • Visual Studio 2015 or 2017, it can be the community version, no problems there;
  • CROSS Platform Xamarin Forms project with XAML for pages;
  • Fody PropertyChanged to be installed via nuget; 
Observation
 
This article expects that you have already done some implementation with MVVM design Pattern in Xamarin Forms.
 
Traditional MVVM INotifyPropertyChanged in Xamarin Forms
  1. public class TradicionalPageViewModel : INotifyPropertyChanged  
  2.     {  
  3.         public event PropertyChangedEventHandler PropertyChanged;  
  4.    
  5.         protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "")  
  6.         {  
  7.             PropertyChanged?.Invoke(thisnew PropertyChangedEventArgs(propertyName));  
  8.         }  
  9.    
  10.         private string _title;  
  11.         public string Title
  12.         {  
  13.             get  
  14.             {  
  15.                 return _title;  
  16.             }  
  17.             set  
  18.             {  
  19.                 if (_title!= value)  
  20.                 {  
  21.                     _title= value;  
  22.                     NotifyPropertyChanged();  
  23.                 }  
  24.             }  
  25.         }  
  26.    
  27.         private string _name;  
  28.         public string Name
  29.         {  
  30.             get  
  31.             {  
  32.                 return _name;  
  33.             }  
  34.             set  
  35.             {  
  36.                 if (_name!= value)  
  37.                 {  
  38.                     _name= value;  
  39.                     NotifyPropertyChanged();  
  40.                 }  
  41.             }  
  42.         }  
  43.    
  44.         private int _age;  
  45.         public int Age  
  46.         {  
  47.             get  
  48.             {  
  49.                 return _age;  
  50.             }  
  51.             set  
  52.             {  
  53.                 if (_age!= value)  
  54.                 {  
  55.                     _age= value;  
  56.                     NotifyPropertyChanged();  
  57.                 }  
  58.             }  
  59.         }  
  60.     }  
The code above is the traditional pattern, that is, the “spartan way” where you’ll need, for each property, to implement all the setter rules of each property of your ViewModel, in addition to implementing the interface INotifyPropertyChanged with the event that will notify the ViewModel changes.
 
It’s certain that the template above doesn't follow the principles of DRY (Don’t Repeat Yoursefl), so to facilitate it there are some alternatives, one of them is shown below by the folks of the Xamarin Marathon, specifically the MVVM video of Alexandre Chofi and James Montemagno. 
 
Alternative MVVM INotifyPropertyChanged in Xamarin Forms
  1. public class MarathonPageViewModel : BaseViewModel  
  2.     {  
  3.         private string _title;  
  4.         public string Title
  5.         {  
  6.             get  
  7.             {  
  8.                 return _title;  
  9.             }  
  10.             set  
  11.             {  
  12.                 SetProperty(ref _title, value);  
  13.             }  
  14.         }  
  15.    
  16.         private string _name;  
  17.         public string Name
  18.         {  
  19.             get  
  20.             {  
  21.                 return _name;  
  22.             }  
  23.             set  
  24.             {  
  25.                 SetProperty(ref _name, value);  
  26.             }  
  27.         }  
  28.    
  29.         private int _age;  
  30.         public int Age  
  31.         {  
  32.             get  
  33.             {  
  34.                 return _age;  
  35.             }  
  36.             set  
  37.             {  
  38.                 SetProperty(ref _age, value);  
  39.             }  
  40.         }  
  41.     }    
Alexandre Chofi created a base class and some methods to be used on each ViewModel Property facilitating its use and repeating less code. Of course, the code became very clean and easy to use.
 
BaseViewModel Class from Xamarin Brazil Marathon
  1. public class BaseViewModel : INotifyPropertyChanged  
  2.     {  
  3.         public event PropertyChangedEventHandler PropertyChanged;  
  4.    
  5.         protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)  
  6.         {  
  7.             PropertyChanged?.Invoke(thisnew PropertyChangedEventArgs((propertyName)));  
  8.         }  
  9.    
  10.         protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)  
  11.         {  
  12.             if (EqualityComparer<T>.Default.Equals(storage, value))  
  13.             {  
  14.                 return false;  
  15.             }  
  16.             storage = value;  
  17.             OnPropertyChanged(propertyName);  
  18.    
  19.             return true;  
  20.         }  
  21.     }  
This morning I had an idea to simplify this INotifyPropertyChanged thing, so I woke up early and started looking and unsurprisingly something appears ready to use.

So, for those developers who are more eclectic, there exists an alternative that's even simpler, I’m speaking of Fody PropertyChanged library.
 
MVVM INotifyPropertyChanged with Fody PropertyChanged in Xamarin Forms,
  1. [ImplementPropertyChanged]  
  2.     public class HomePageViewModel  
  3.     {  
  4.         public string Title { getset; }  
  5.         public string Name { getset; }  
  6.         public int Age { getset; }  
  7.     }  
As you can see above, I really don’t know if something simpler than this exists. We just add the attribute [ImplementPropertyChanged] to the ViewModel at the compile time, the Fody PropertyChanged will inject the necessary code in the setter of each public property of the ViewModel.
 
Make sure to remember that the thing is not dynamic, that is, it will not affect the performance of your application because it’s on the compile-time not on execution. Do you believe it? Take a look at the code below caught from .NET Reflector: 
  1. namespace FSL.XF5.ViewModels  
  2. {  
  3.     using System;  
  4.     using System.ComponentModel;  
  5.     using System.Diagnostics;  
  6.     using System.Runtime.CompilerServices;  
  7.     using System.Threading;  
  8.    
  9.     public class HomePageViewModel : INotifyPropertyChanged  
  10.     {  
  11.         [DebuggerBrowsable((DebuggerBrowsableState) DebuggerBrowsableState.Never), CompilerGenerated]  
  12.         private string <Title>k__BackingField;  
  13.    
  14.         [field: NonSerialized]  
  15.         public event PropertyChangedEventHandler PropertyChanged;  
  16.    
  17.         public virtual void OnPropertyChanged(string propertyName)  
  18.         {  
  19.             PropertyChangedEventHandler propertyChanged = this.PropertyChanged;  
  20.             if (propertyChanged != null)  
  21.             {  
  22.                 propertyChanged(thisnew PropertyChangedEventArgs(propertyName));  
  23.             }  
  24.         }  
  25.    
  26.         public string Title
  27.         {  
  28.             [CompilerGenerated]  
  29.             get  
  30.             {  
  31.                 return this.<Title>k__BackingField;  
  32.             }  
  33.             [CompilerGenerated]  
  34.             set  
  35.             {  
  36.                 if (!string.Equals(this.<Title>k__BackingField, value, (StringComparison) StringComparison.Ordinal))  
  37.                 {  
  38.                     this.<Title>k__BackingField = value;  
  39.                     this.OnPropertyChanged("Titulo");  
  40.                 }  
  41.             }  
  42.         }  
  43.     }  
  44. }   
This implementation code is on my GitHub and you can download it now. Simplifying INotifyPropertyChanged: Suggestions or Criticism are always welcome. To know more about Fody PropertyChanged click here

An important feedback from a college and member of the community
 
"In addition to the content well shown, I point out the existence of a certain procedure that requires to be executed when using IDE like Xamarin Studio. In this, after the installation of the Nuget Packge and the creation of the FodyWeavers.xml file in the root of the project, it’s necessary the addition of a simple XML TAG for the processing of PropertyChanged be done correctly, it’s necessary to add the TAG below. 
  1. <PropertyChanged  />  
Also important, is to pay attention for updates on Fody and PropertyChanged package, for those focused on PropertyChanged package, update the Fody only when the update is requested by the PropertyChaned itself, otherwise keep a library Fody as it is. Users of mono version 5 or superior, it’s mandatory to be using the latest version of the PorpertyChanged package(together with the latest of Fody for its dependency), to solve conflicts with Cecil(Mono) dependency’s.Rodrigo Amaro 
 
Good studies and farewell!


Similar Articles