How can I get a reference to the object changed in a PropertyValueChanged event?

Viewed 126

I can add a handler for the PropertyValueChanged event on my PropertyGrid. If the user changes properties of the SelectedObject, this works fine. However if the SelectedObject has properties which are themselves objects, the user can also edit properties of that object. I still get the PropertyValueChanged event raised which is good, but I can't find a way of getting a reference to the object that they have changed.

Viewing the ChangedItem property of the PropertyValueChangedEventArgs parameter in the Watch window, I can see that there is an Instance property in PropertyDescriptorGridEntry but I don't seem to be able to access this from my code.

Any suggestions appreciated.

2 Answers

When the PropertyValueChanged event is raised, it has an associated PropertyValueChangedEventArgs. This object has a ChangedItem member that holds the GridItem that was changed. So if you want to do something with the changed item, your handler could look like:

private void OnPropertyValueChanged(Object sender, PropertyValueChangedEventArgs args) {
    Console.WriteLine($"The changed item was {args.ChangedItem}");
}

This seems to do the job:

e.ChangedItem.GetType().GetProperty("Instance").GetValue(e.ChangedItem)
Related