Use reflection to get the actual value of the property reported by INotifyPropertyChanged?

I am working on a project that will use INotifyPropertyChanged to declare property changes for subscriber classes.

 void item_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "Quantity") .... 

It seems to me that when a signing class receives a notification, the only available value that it can receive is the name of the property. Is there a way to get a reference to an actual object that has a property change? Then I can get the new value of this property from the link. Maybe using reflection?

Could someone write a code snippet to help me? Very much appreciated.

+7
reflection c # inotifypropertychanged
source share
2 answers

Actual sender object (at least it should be):

 void item_PropertyChanged(object sender, PropertyChangedEventArgs e) { var propertyValue = sender.GetType().GetProperty(e.PropertyName).GetValue(sender); } 

If you care about performance, then sender.GetType().GetProperty(e.PropertyName) caches the results.

+9
source share

Note. This interface is primarily a data binding API, and data binding is not limited to simple models such as reflection. Therefore, I suggest you use the TypeDescriptor API. This will allow you to correctly identify changes for both simple and complex models:

 var prop = TypeDescriptor.GetProperties(sender)[e.PropertyName]; if(prop != null) { object val = prop.GetValue(sender); //... } 

(with directive using System.ComponentModel; )

+8
source share

All Articles