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?
I really like Marc's solution, but I think it can be slightly improved to avoid using a "magic string" (which doesn't support refactoring). Instead of using the property name as a string, it's easy to make it a lambda expression :
Just add the following methods to Marc's code, it will do the trick :
BTW, this was inspired by
this blog postupdated URLIf you are using dynamics in .NET 4.5 you don't need to worry about
INotifyPropertyChanged
.if Name is bound to some control it just works fine.
Without using something like postsharp, the minimal version I use uses something like:
Each property is then just something like:
which isn't huge; it can also be used as a base-class if you want. The
bool
return fromSetField
tells you if it was a no-op, in case you want to apply other logic.or even easier with C# 5:
which can be called like this:
with which the compiler will add the
"Name"
automatically.C# 6.0 makes the implementation easier:
...and now with C#7:
I think people should pay a little more attention to performance, it really does impact the UI when there are a lot of objects to be bind (think of a grid with 10,000+ rows) or if the object's value changes frequently (realtime monitoring app).
I took various implementation found here and elsewhere and did a comparison, check it out perfomance comparison of INotifyPropertyChanged implementations.
Here is a peek at the result
Use this
}
Whilst there are obviously lots of ways to do this, with the exception of the AOP magic answers, none of the answers seem to look at setting a Model's property directly from the view model without having a local field to reference.
The issue is you can't reference a property. However, you can use an Action to set that property.
This can be used like the following code extract.
Check out this BitBucket repo for a full implementation of the method and a few different ways of achieving the same result, including a method that uses LINQ and a method that uses reflection. Do note that these methods are slower performance wise.