7

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.

Thilina H
  • 5,754
  • 6
  • 26
  • 56
Jason
  • 821
  • 2
  • 16
  • 28
  • 5
    `sender` might be the one. – AgentFire Dec 25 '13 at 07:25
  • Why not simply extend PropertyChangedEventArgs to also carry the value you are interested in? You can make the extending class generic. – slugster Dec 25 '13 at 07:39
  • 1
    @slugster: this makes sense only when subscribers know about custom `PropertyChangedEventArgs` descendants. For example, binding engines are not such ones. – Dennis Dec 25 '13 at 07:49

2 Answers2

11

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.

Dennis
  • 37,026
  • 10
  • 82
  • 150
10

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)

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900