Skip to content

Instantly share code, notes, and snippets.

@mpfund
Created June 23, 2014 11:52
Show Gist options
  • Save mpfund/cac0c49d808b3d00f96d to your computer and use it in GitHub Desktop.
Save mpfund/cac0c49d808b3d00f96d to your computer and use it in GitHub Desktop.
public static void RemoveDelegateFromEvent(object target, string EventPropertyName)
{
var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance |BindingFlags.Static;
var ev = target.GetType().GetEvent(EventPropertyName, bindingFlags);
var f1 = target.GetType().GetField(EventPropertyName, bindingFlags);
// search in base class
if (f1 == null)
f1 = target.GetType().BaseType.GetField(EventPropertyName, bindingFlags);
if (f1 == null)
throw new Exception("can't detach event handler");
var del = f1.GetValue(target) as Delegate;
if(del != null)
ev.RemoveEventHandler(target, del);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment