Using the MVVM pattern is a great way to organise your Xamarin.Forms app – certainly not the latest or only way, but usually a good choice.

It will help you to separate concerns, help with testability and general good organisation of your code base. You’ll get very comfortable with using Binding to get that data from your ViewModels into the Views. There is, however, a small downside to all that Binding goodness.

PropertyChanged

Every time a property value changes, there has to be some mechanism for the View to find out about the change (or the other way around). Enter INotifyPropertyChanged. Implementing this interface is the key to raising these notifications. Unfortunately this soon becomes very tiresome.

Open up Visual Studio 2019 and create a new Xamarin.Forms project, choosing any template with sample data such as the Master-Detail.

Taking a look at the project that was created, we can see an implementation of the MVVM pattern, complete with Views and ViewModels. The tiresome bit is hidden in the BaseViewModel. Implementing INotifyPropertyChanged means that binding for those properties will work even as values change, but requires calling that SetProperty method and raising events every time something changes. Pop a breakpoint in there and step through the running app to see what I mean.

Weaving

As elegant as the Visual Studio team’s solution is, there is a much easier way, if you are willing to accept a little ‘black-box’ magic.

Weaving is the process of injecting boilerplate code into your MSIL (Microsoft Intermediate Language and one of the steps involved in compiling .Net).

Fody

Fody is an extensible library for weaving .NET created by Simon Cropp.

Simply add the PropertyChanged.Fody package to your project and get to work deleting code 🙂

Take the BaseViewModel for example. You can now replace the boilerplate with a couple of simple auto-properties and you are done.

Check out https://github.com/Fody/Home for more information about this awesome library.

Advertisement