Tuesday, October 11, 2016

PropertyChanged.Fody

Short story
When using MVVM as the pattern of choice for your app, make sure to use PropertyChanged.Fody to make your life a little easier. 
  1. Install the nuget-package PropertyChanged.Fody
  2. If using Xamarin studio, edit the Weavers.xml file in the root and add <PropertyChanged>. This is done automatically in Visual Studio.
  3. Create a base class for ViewModels and decorate it with the [ImplementPropertyChanged]attribute
  4. All your properties will be raising the PropertyChanged event on INotifyPropertyChanged.
Long story
MVVM heavily relies on ViewModels that implement INotifyPropertyChanged. This is the way that the View will be aware of changes in the ViewModel and what triggers UI-updates when you change a ViewModel property.

Before PropertyChanged.Fody

The usual way to tackle this is to implement the INotifyPropertyChanged your self. INotifyPropertyChanged only defines one event called PropertyChanged. This event is what the view hooks up to in order to listen to the ViewModel. No magic at all going on here.
So what we do is that we implement that interface and add a method to raise it in a simple way.
using System.ComponentModel; // The definition lives here

public class MyViewModel : INotifyPropertyChanged
{
    // The only thing INotifyPropertyChanged defines
    public event PropertyChangedEventHandler PropertyChanged;
   
    // Helper method to raise the event
    protected void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    
    // And a property with a backing field
    private string _name;
    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
            RaisePropertyChanged("Name");
        }
    }
} 
That is alot of code for a single property. What if we could get rid of most of that? 

After PropertyChanged.Fody

Enter PropertyChanged.Fody!
To install, do this:
  1. Install the nuget-package PropertyChanged.Fody
  2. If using Xamarin studio, edit the Weavers.xml file in the root and add <PropertyChanged>. This is done automatically in Visual Studio.
After installing the nuget package, rewrite the code above to look like this.
[ImplementPropertyChanged]
public class MyViewModel 
{
    public string Name {get; set; }
} 

Can we make it better

Yes, create a base class for your ViewModels and decorate that one with the ImplementPropertyChanged attribute. Then you can forget about it.

How does it work

Fody is an IL-weaver. It modifies the IL code generated by the compiler and implements the interface for you.

Resources

Make sure to check out the official documentation at https://github.com/Fody/PropertyChanged