Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

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

Would anyone mind writing a code snippet to help me out? Greatly appreciated.

like image 427
Jason Avatar asked Dec 25 '13 07:12

Jason


2 Answers

Actual object is sender (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 cache sender.GetType().GetProperty(e.PropertyName) results.

like image 112
Dennis Avatar answered Nov 10 '22 00:11

Dennis


Note: this interface is primarily a data-binding API, and data-binding is not limited to simple models like reflection. As such, I would suggest you use the TypeDescriptor API. This will allow you to correctly detect changes for both simple and complex models:

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

(with a using System.ComponentModel; directive)

like image 41
Marc Gravell Avatar answered Nov 09 '22 22:11

Marc Gravell