PropertyChanged.SourceGenerator

Implementing INotifyPropertyChanged / INotifyPropertyChanging is annoying. PropertyChanged.SourceGenerator hooks into your compilation process to generate the boilerplate for you, automatically.
PropertyChanged.SourceGenerator works well if you're using an MVVM framework or going without, and supports various time-saving features such as:
- Automatically notifying dependent properties.
- Calling hooks when particular properties change.
- Keeping track of whether any properties have changed.
Table of Contents
- Installation
- Quick Start
- Versioning
- Defining your ViewModel
- Defining Properties
- Property Names
- Property Accessibility
- Property Doc Comments
- Attributes on Generated Properties
- Property Dependencies
- Automatic Dependencies
- Manual Dependencies with
[DependsOn]
- Manual Dependencies with
[AlsoNotify]
- Property Changed Hooks
- Type Hooks with
OnPropertyChanged / OnPropertyChanging
- Property Hooks with
On{PropertyName}Changed / On{PropertyName}Changing
- Change Tracking with
[IsChanged]
- Configuration
- Generated Property Names
OnPropertyChanged / OnPropertyChanging Method Name
- Automatic Dependencies
- Contributing
- Comparison to PropertyChanged.Fody
Installation
PropertyChanged.SourceGenerator is available on NuGet. You'll need to be running Visual Studio 2019 16.9 or higher, or by building using the .NET SDK 5.0.200 or higher (your project doesn't have to target .NET 5, you just need to be building using a newish version of the .NET SDK).
These dependencies may change in future minor versions, see Versioning.
If you're using Visual Studio 17.2.6 with WPF and you get lots of "... already contains a definition for ..." error messages, see this bug and workaround.
Quick Start
using PropertyChanged.SourceGenerator;
public partial class MyViewModel
{
[Notify] private string _lastName;
public string FullName => $"Dr. {LastName}";
}
Make sure your ViewModel is partial, and define the backing fields for your properties, decorated with [Notify]. When you build your project, PropertyChanged.SourceGenerator will create a partial class which looks something like:
partial class MyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string LastName
{
get => _lastName;
set
{
if (!EqualityComparer<string>.Default.Equals(_lastName, value))
{
_lastName = value;
OnPropertyChanged(EventArgsCache.LastName);
OnPropertyChanged(EventArgsCache.FullName);
}
}
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
{
PropertyChanged?.Invoke(args);
}
}
What happened there?
- PropertyChanged.SourceGenerator spotted that you defined a partial class and at least one property was decorated with
[Notify], so it got involved and generated another part to the partial class.
- It noticed that you hadn't implemented
INotifyPropertyChanged, so it implemented it for you (it's also fine if you implement it yourself).
- For each field decorated with
[Notify], it generated property with the same name (but with the leading _ removed and the first letter capitalised) which used that field as its backing field. That property implemented INotifyPropertyChanged.
- It noticed that
FullName depended on LastName, so raised the PropertyChanged event for FullName whenever LastName changed.
Note: It's really important that you don't refer to the backing fields after you've defined them: let PropertyChanged.SourceGenerator generate the corresponding properties, and then always use those propertues.
Versioning
Source Generators are a relatively new technology, and they're being improved all the time. Unfortunately, in order for source generators to take advantage of improvements, they must target a newer version of Visual Studio / the .NET SDK.
If/when PropertyChanged.SourceGenerator is updated to depend on a new version Visual Studio / the .NET SDK, this will be signified by a minor version bump: the minor version number will be incremented. Changes which mean you have to change existing code to keep PropertyChanged.SourceGenerator working will be signified by a major version bump.
| Version Number |
Min Visual Studio Version |
Min .NET SDK Version |
| 1.0.x |
2019 16.9 |
5.0.200 |
| 1.1.x |
2022 17.3 |
6.0.304 |
Defining your ViewModel
INotifyPropertyChanged
When you define a ViewModel which makes use of PropertyChanged.SourceGenerator, that ViewModel must be partial. If it isn't, you'll get a warning.
Your ViewModel can implement INotifyPropertyChanged, or not, or it can implement parts of it (such as implementing the interface but not defining the PropertyChanged event), or it can extend from a base class which implements INotifyPropertyChanged: PropertyChanged.SourceGenerator will figure it out and fill in the gaps.
If you've got a ViewModel base class which implements INotifyPropertyChanged (perhaps as part of an MVVM framework), PropertyChanged.SourceGenerator will try and find a suitable method to call in order to raise the PropertyChanged event. It will look for a method called OnPropertyChanged, RaisePropertyChanged, NotifyOfPropertyChange, or NotifyPropertyChanged, which covers all of the major MVVM frameworks (although this is configurable, see Configuration), with one of the following signatures:
void OnPropertyChanged(PropertyChangedEventArgs args)
void OnPropertyChanged(string propertyName)
void OnPropertyChanged(PropertyChangedEventArgs args, object oldValue, object newValue)
void OnPropertyChanged(string propertyName, object oldValue, object newValue)
If it can't find a suitable method, you'll get a warning and it won't run on that particular ViewModel.
INotifyPropertyChanging
Working with INotifyPropertyChanging is similar, with the caveat that your class or one of its base classes must implement INotifyPropertyChanging (not everone wants to implement this interface, so it's opt-in). You don't need to implement all of the interface members: PropertyChanged.SourceGenerator will step in and fill in the gaps.
As with INotifyPropertyChanged, PropertyChanged.SourceGenerator will try and find a suitable method to call in order to raise the PropertyChanging event. It will look for a method called OnPropertyChanging, RaisePropertyChanging, NotifyOfPropertyChanging, or NotifyPropertyChanging (again this is configurable, see Configuration), with one of the following signatures:
void OnPropertyChanging(PropertyChangingEventArgs args)
void OnPropertyChanging(string propertyName)
void OnPropertyChanging(PropertyChangingEventArgs args, object oldValue)
void OnPropertyChanging(string propertyName, object oldValue)
Defining Properties
To get PropertyChanged.SourceGenerator to generate a property which implements INotifyPropertyChanged, you must define the backing field for that property, and decorate it with [Notify].
(This is an annoying effect of how Source Generators work. If you'd like a better way, please vote for this issue on partial properties).
If you write:
using PropertyChanged.SourceGenerator;
public partial class MyViewModel : INotifyPropertyChanged
{
[Notify] private int _foo;
}
PropertyChanged.SourceGenerator will generate something like:
partial class MyViewModel
{
public int Foo
{
get => _foo,
set
{
if (!EqualityComparer<int>.Default.Equals(_foo, value))
{
_foo = value;
OnPropertyChanged(EventArgsCache.Foo);
}
}
}
// PropertyChanged event, OnPropertyChanged method, etc.
}
Property Names
The name of the generated property is derived from the name of the backing field, by:
- Removing a
_ prefix, if one exists
- Changing the first letter to upper-case
This can be customised, see Configuration.
If you want to manually specify the name of a particular property, you can pass a string to [Notify]:
using PropertyChanged.SourceGenerator;
public partial class MyViewModel : INotifyPropertyChanged
{
[Notify("FOO")] private int _foo;
}
PropertyChanged.SourceGenerator will generate a property called FOO.
Property Accessibility
By default, all generated properties have public getters and public setters.
This isn't always what you want, so it's possible to override this by passing Getter.XXX and Setter.XXX to [Notify].
using PropertyChanged.SourceGenerator;
public partial class MyViewModel : INotifyPropertyChanged
{
[Notify(Setter.Private)]
private int _foo;
[Notify(Getter.PrivateProtected, Setter.Protected)]
private string _bar;
}
This generates:
partial class MyViewModel
{
public int Foo
{
get => _foo
private set { /* ... */ }
}
protected string Bar
{
private protected get => _bar,
set { /* ... */ }
}
}
Property Doc Comments
Any XML doc comments applied to your field will be copied to the generated property. Note that any such comments must appear before the [Notify] attribute.
using PropertyChanged.SourceGenerator;
public partial class MyViewModel
{
/// <summary>
/// The Foo property
/// </summary>
[Notify] private int _foo;
}
Generates:
partial class MyViewModel
{
/// <summary>
/// The Foo property
/// </summary>
public int Foo
{
// ...
}
}
Attributes on Generated Properties
Sometimes you need the to place attributes onto the generated property, e.g. to control validation or serialization. You can do this by passing a string containing this attribute to the [PropertyAttribute] attribute, e.g.:
using PropertyChanged.SourceGenerator;
public partial class MyViewModel
{
[PropertyAttribute("[System.Xml.Serialization.XmlIgnore]")]
[Notify] private int _foo;
}
The string that you pass to [PropertAttribute] will be pasted into the generated file verbatim. It's important to note that the generated file doesn't have any using statements, so you need to fully-qualify all types. For example:
[PropertyAttribute("[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]")]
rather than just:
[PropertyAttribute("[EditorBrowsable(EditorBrowsabeState.Never)]")]
Virtual Properties
If you want the generated property to be virtual, use:
using PropertyChanged.SourceGenerator;
public partial class MyViewModel : INotifyPropertyChanged
{
[Notify(IsVirtual = true]
private int _foo;
}
Generates:
partial class MyViewModel
{
public virtual int Foo
{
// ...
}
}
Property Dependencies
Sometimes, you have properties which depend on other properties, for example:
using PropertyChanged.SourceGenerator;
public partial class MyViewModel
{
[Notify] private string _firstName;
[Notify] private string _lastName;
public string FullName => $"{FirstName} {LastName}";
}
Whenever FirstName or LastName is updated, you want to raise a PropertyChanged event for FullName, so that the UI also updates the value of FullName which is displayed.
Automatic Dependencies
If a property has a getter which accesses a generated property on the same type, then PropertyChanged.SourceGenerator will automatically raise a PropertyChanged event every time the property it depends on changes.
For example, if you write:
using PropertyChanged.SourceGenerator;
public partial class MyViewModel
{
[Notify] private string _lastName;
public string FullName => $"Dr. {LastName}";
}
PropertyChanged.SourceGenerator will notice that the getter for FullName accesses the generated LastName