This limits the use of anonymous methods as event handlers. They cannot be deleted in the same way as a regular method (which is automatically created by a delegate instance by converting a group of methods), since anonymous methods are compiled into the container class created by each instance, and a new instance of the class is created each time.
To save the action parameter, you can create a container class that will have a delegate for your event handler inside. A class can be declared private in another class that you are working with, or made internal, possibly in the Helpers namespace. It will look something like this:
class DelegateContainer { public DelegateContainer(Action theAction, string propName) { TheAction = theAction; PopertyName = propName; } public Action TheAction { get; private set; } public string PropertyName { get; private set; } public void PropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if(PropertyName == e.PropertyName) TheAction(); } }
Then create and save the container reference in your class. You can create a static member currentContainer , and then set the handler as follows:
private static DelegateContainer currentContainer; public static void OnPropertyChanged<T>(this INotifyPropertyChanged target, string propertyName, Action action) { if (target == null) { return; } if(currentContainer != null) target.PropertyChanged -= currentContainer.PropertyChangedHandler; currentContainer = new DelegateContainer(action, propertyName); target.PropertyChanged += currentContainer.PropertyChangedHandler; }
Mike dinescu
source share