
Introducing PropertyChanged.Fody
The traditional way of implementing a ViewModel is to inherit from a base class (such as the ViewModel that we defined previously) and then add code that might look as follows:
public class MyTestViewModel : ViewModel
{
private string name;
public string Name
{
get { return name; }
set { name = value; RaisePropertyChanged(nameof(Name)); }
}
}
Each property that we want to add to a ViewModel yields six lines of code. Not too bad, you might think. However, considering that a ViewModel could potentially contain 10 to 20 properties, this rapidly turns into a lot of code. We can do better than this.
In just a few simple steps, we can use a tool called PropertyChanged.Fody to automatically inject almost all the code during the build process:
- In the .NET Standard library, install the PropertyChanged.Fody NuGet package.
- Create a file called FodyWeavers.xml and add the following XML to it:
<?xml version="1.0" encoding="utf-8" ?>
<Weavers>
<PropertyChanged />
</Weavers>
PropertyChanged.Fody will scan the assembly for any class that implements the INotifyPropertyChanged interface and adds the code needed to raise the PropertyChanged event. It will also take care of dependencies between properties, meaning that if you have a property that returns values based on two other properties, it will be raised if either of those two values changes.
The result is that the test class we had previously is reduced to a single line of code per property. This makes the code base more readable because everything happens behind the scenes:
public class MyTestViewModel : ViewModel
{
public string Name { get; set; }
}