The traditional way of implementing a ViewModel class is to inherit it from a base class (such as the ViewModel class 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
{
if (name != value)
{
name = value;
RaisePropertyChanged(nameof(Name));
}
}
}
}
Each property that we want to add to a ViewModel class yields 13 lines of code. Not too bad, you might think. However, considering that a ViewModel class 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 in the root of the .NET Standard library and add the following XML to it:
<?xml version="1.0" encoding="utf-8" ?>
<Weavers>
<PropertyChanged />
</Weavers>
PropertyChanged.Fody scans the assembly for any class that implements the INotifyPropertyChanged interface and adds the code needed to raise the PropertyChanged event. It also takes care of dependencies between properties, meaning if you have a property that returns values based on two other properties, it is 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; }
}