Automatically INotifyPropertyChanged

Tim Gradwell picture Tim Gradwell · Feb 9, 2009 · Viewed 30.6k times · Source

Is there any way to automatically get notified of property changes in a class without having to write OnPropertyChanged in every setter? (I have hundreds of properties that I want to know if they have changed).


Anton suggests dynamic proxies. I've actually used the "Castle" library for something similar in the past, and while it does reduce the amount of code I've had to write, it added around 30 seconds to my program startup time (ymmv) - because it's a runtime solution.

I'm wondering if there is a compile time solution, maybe using compile-time attributes...


Slashene and TcKs give suggestions which generates repetitive code - unfortunately, not all my properties are a simple case of m_Value = value - lots of them have custom code in the setters, so cookie-cutter code from snippets and xml aren't really feasible for my project either.

Answer

Isak Savo picture Isak Savo · Nov 1, 2011

EDIT: The author of NotifyPropertyWeaver has deprecated the tool in favor of the more general Fody. (A migration guide for people moving from weaver to fody is available.)


A very convenient tool I've used for my projects is Notify Property Weaver Fody.

It installs itself as a build step in your projects and during compilation injects code that raises the PropertyChanged event.

Making properties raise PropertyChanged is done by putting special attributes on them:

[ImplementPropertyChanged]
public string MyProperty { get; set; }

As a bonus, you can also specify relationships for properties that depend on other properties

[ImplementPropertyChanged]
public double Radius { get; set; }

[DependsOn("Radius")]
public double Area 
{
    get { return Radius * Radius * Math.PI; }
}