Xamarin: The magic of Fody weaving

When creating Xamarin apps a lot of people choose to go with the MVVM pattern. There are a lot of beautiful frameworks out there to make the life of an MVVM developer easier, but sometimes you just want to do it the hard way and write it yourself.

If you ever created an Xamarin app using the MVVM pattern (without any framework) and data binding, you may have noticed there is a lot of boilerplate code to notify property changes. As your ViewModels grow, this becomes a nightmare!

Fody.PropertyChanged to the rescue!
Fody is an extensible library that adds an post build task to the MSBuild pipeline. With this task it manipulates the generated IL code, depending on what add-ins you are using. Add-ins can be build on the Fody core. One of the add-ins is Fody.PropertyChanged. As you might guess, this add-in generates the code for notifying changes in a ViewModel. The add-in will look for properties in classes that implement INotifyPropertyChanged or properties/classes annotated with the [ImplementPropertyChanged] attribute.

Example class PersonViewModel:

[ImplementPropertyChanged]
public class PersonViewModel
{
public string GivenNames { get; set; }
public string FamilyName { get; set; }

public string FullName
{
get
{
return string.Format("{0} {1}", GivenNames, FamilyName);
}
}
}

After applying Fody magic it will become:

public class PersonViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

string givenNames;
public string GivenNames
{
get { return givenNames; }
set
{
if (value != givenNames)
{
givenNames = value;
OnPropertyChanged("GivenNames");
OnPropertyChanged("FullName");
}
}
}

string familyName;
public string FamilyName
{
get { return familyName; }
set
{
if (value != familyName)
{
familyName = value;
OnPropertyChanged("FamilyName");
OnPropertyChanged("FullName");
}
}
}

public string FullName
{
get
{
return string.Format("{0} {1}", GivenNames, FamilyName);
}
}

public virtual void OnPropertyChanged(string propertyName)
{
var propertyChanged = PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}

Fody.PropertyChanged has another killer feature called Fody NotificationInterception which makes it possible to execute some code before propertyChanged gets triggered. This feature can be for example used for logging purpose or to make sure you are calling propertyChanged on the main thread. See related links for more info.

If you want to give Fody.PropertyChanged (or any other Fody add-in) a try, just install the NuGet package and you’re good to go!

Note:
Fody requires your release builds to contain debug symbols. You can enable this in your project settings by setting Build->compiler->debug information to “Symbols only”.

Fody-release

Related links:

Leave a comment