经过多方试验,终于找到下面的方法,可以移动诸如Window上的Closed事件注册的处理方法。这个是行之有效的,记录下来,以备后用。上代码:
void ClearEvent(Control control, string eventname)
{
if (control == null) return;
if (string.IsNullOrEmpty(eventname)) return;
BindingFlags mPropertyFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic;
BindingFlags mFieldFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.Static;
Type controlType = control.GetType();
PropertyInfo propertyInfo = controlType.GetProperty("Events", mPropertyFlags);
if (propertyInfo == null)
{
Type baseType = control.GetType(); ;
while ((baseType = baseType.BaseType) != typeof(object) && propertyInfo == null)
{
propertyInfo = baseType.GetProperty("Events", mPropertyFlags);
}
}
EventHandlerList eventHandlerList = (EventHandlerList)propertyInfo.GetValue(control, null);
FieldInfo fieldInfo = control.GetType().GetField("Event_" + eventname, mFieldFlags);
if (fieldInfo == null)
{
Type baseType = control.GetType();
while ((baseType = baseType.BaseType) != typeof(object) && fieldInfo == null)
{
fieldInfo = baseType.GetField("Event_" + eventname, mFieldFlags);
}
}
Delegate d = eventHandlerList[fieldInfo.GetValue(control)];
if (d == null) return;
EventInfo eventInfo = controlType.GetEvent(eventname);
foreach (Delegate dx in d.GetInvocationList())
eventInfo.RemoveEventHandler(control, dx);
}
调用如下:
var myWin = new MyWindow();
ClearEvent(myWin , "Closed");