Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top