Microsoft should have implemented something snappy for INotifyPropertyChanged
, like in the automatic properties, just specify {get; set; notify;}
I think it makes a lot of sense to do it. Or are there any complications to do it?
Can we ourselves implement something like 'notify' in our properties. Is there a graceful solution for implementing INotifyPropertyChanged
in your class or the only way to do it is by raising the PropertyChanged
event in each property.
If not can we write something to auto-generate the piece of code to raise PropertyChanged
event?
Look here : http://dotnet-forum.de/blogs/thearchitect/archive/2012/11/01/die-optimale-implementierung-des-inotifypropertychanged-interfaces.aspx
It's written in German, but you can download the ViewModelBase.cs. All the comments in the cs-File are written in English.
With this ViewModelBase-Class it is possible to implement bindable properties similar to the well known Dependency Properties :
Let me introduce my own approach called Yappi. It belongs to Runtime proxy|derived class generators, adding new functionality to an existing object or type, like Caste Project's Dynamic Proxy.
It allows to implement INotifyPropertyChanged once in base class, and then declare derived classes in following style, still supporting INotifyPropertyChanged for new properties:
Complexity of derived class or proxy construction can be hidden behind the following line:
And all INotifyPropertyChanged implementation work can be done like this:
It is fully safe for refactoring, uses no reflection after type construction and fast enough.
I resolved in This Way (it's a little bit laboriouse, but it's surely the faster in runtime).
In VB (sorry, but I think it's not hard translate it in C#), I make this substitution with RE:
with:
This transofrm all code like this:
In
And If I want to have a more readable code, I can be the opposite just making the following substitution:
With
I throw to replace the IL code of the set method, but I can't write a lot of compiled code in IL... If a day I write it, I'll say you!
A very AOP-like approach is to inject the INotifyPropertyChanged stuff onto an already instantiated object on the fly. You can do this with something like Castle DynamicProxy. Here is an article that explains the technique:
Adding INotifyPropertyChanged to an existing object
Another Idea...
I came up with this base class to implement the observable pattern, pretty much does what you need ("automatically" implementing the set and get). I spent line an hour on this as prototype, so it doesn't have many unit tests, but proves the concept. Note it uses the
Dictionary<string, ObservablePropertyContext>
to remove the need for private fields.Here's the usage