Alex Rivera | Logout

Automatically INotifyPropertyChanged

Asked 2009-02-09T09:59:10.710
67

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.

Edit
Report

2 Answers

4

you might want to look into Aspect-Oriented Programming as a whole

Frameworks => you could look at linfu

answered 2010-05-17T13:33:47.367
1

Just to make the implementation quicker you can use a snippet

From http://aaron-hoffman.blogspot.it/2010/09/visual-studio-code-snippet-for-notify.html

the ViewModel classes of projects following the M-V-VM pattern it is often necessary to raise a "PropertyChanged" event (to assist with INotifyPropertyChanged interface implementation) from within a property's setter. This is a tedious task that will hopefully someday be solved by using the Compiler as a Service...

Snippet core (for which full credit goes to the author, who is not me) is the following

  <Code Language= "csharp "> 
    <![CDATA[public $type$ $property$ 
{ 
    get { return _$property$; } 
    set 
    { 
        if (_$property$ != value) 
        { 
            _$property$ = value; 
            OnPropertyChanged($property$PropertyName); 
        } 
    } 
} 
private $type$ _$property$; 
public const string $property$PropertyName = "$property$";$end$]]> 
</Code> 
answered 2013-05-07T18:09:39.703

Your Answer