public class EventHandlerHelper { public static Delegate GetEventDelegate(RoutedEventHandlerInfo[] rehis, string method_name) { foreach (RoutedEventHandlerInfo rh in rehis) { if (rh.Handler.Method.Name == method_name) { return rh.Handler; } } return null; } public static void RemoveRoutedEventHandler(object sender, RoutedEvent routedEvent, Delegate handler) { BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.InvokeMethod | BindingFlags.GetProperty | BindingFlags.Default | BindingFlags.GetField | BindingFlags.FlattenHierarchy; FieldInfo fi = sender.GetType().GetField("EventHandlersStoreField", bindingFlags); object EventHandlersStoreField_obj = fi.GetValue(sender); object EventHandlersStoreObj = EventHandlersStoreField_obj.GetType().InvokeMember("GetValue", bindingFlags, null, EventHandlersStoreField_obj, new object[] { sender }); EventHandlersStoreObj.GetType().InvokeMember("RemoveRoutedEventHandler", bindingFlags, null, EventHandlersStoreObj, new object[] { routedEvent, handler }); } public static RoutedEventHandlerInfo[] GetRoutedEventHandlers(object sender, RoutedEvent routedEvent) { BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.InvokeMethod | BindingFlags.GetProperty | BindingFlags.Default | BindingFlags.GetField | BindingFlags.FlattenHierarchy; FieldInfo fi = sender.GetType().GetField("EventHandlersStoreField", bindingFlags); object EventHandlersStoreField_obj = fi.GetValue(sender); object EventHandlersStoreObj = EventHandlersStoreField_obj.GetType().InvokeMember("GetValue", bindingFlags, null, EventHandlersStoreField_obj, new object[] { sender }); RoutedEventHandlerInfo[] rhs = (RoutedEventHandlerInfo[])EventHandlersStoreObj.GetType().InvokeMember("GetRoutedEventHandlers", bindingFlags, null, EventHandlersStoreObj, new object[] { routedEvent }); return rhs; } }
RoutedEventHandlerInfo[] rhs = EventHandlerHelper.GetRoutedEventHandlers(sender, FrameworkElement.LoadedEvent); Delegate dd = EventHandlerHelper.GetEventDelegate(rhs, "MainWindow_Loaded"); EventHandlerHelper.RemoveRoutedEventHandler(sender, FrameworkElement.LoadedEvent, dd);