嘗試的"Validating"
代替"gridControl1.Validating"
「
var eventinfo = FoundControls[0].GetType().GetEvent(
"Validating",
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
雖然這有沒有關係,你有附加一個事件處理該事件的事實。你正在接受事件本身,而不是附屬的處理程序。對於eventInfo
變量(其他的添加和刪除其他事件處理程序)您可以做任何有用的事情。
要訪問連接處理程序(基本代表),你需要看一下該事件的實現代碼(使用像Reflector或dotPeek,或使用Microsoft Reference Source反編譯):
public event CancelEventHandler Validating
{
add
{
base.Events.AddHandler(EventValidating, value);
}
remove
{
base.Events.RemoveHandler(EventValidating, value);
}
}
原來的Control
類使用類型爲EventHandlerList
的名爲Events
的屬性來存儲基於密鑰(在此例中爲EventValidating
字段)的所有代表。
要檢索事件的代表,我們應該從Events
財產閱讀:
public static Delegate[] RetrieveControlEventHandlers(Control c, string eventName)
{
Type type = c.GetType();
FieldInfo eventKeyField = GetStaticNonPublicFieldInfo(type, "Event" + eventName);
if (eventKeyField == null)
{
eventKeyField = GetStaticNonPublicFieldInfo(type, "EVENT_" + eventName.ToUpper());
if (eventKeyField == null)
{
// Not all events in the WinForms controls use this pattern.
// Other methods can be used to search for the event handlers if required.
return null;
}
}
object eventKey = eventKeyField.GetValue(c);
PropertyInfo pi = type.GetProperty("Events",
BindingFlags.NonPublic | BindingFlags.Instance);
EventHandlerList list = (EventHandlerList)pi.GetValue(c, null);
Delegate del = list[eventKey];
if (del == null)
return null;
return del.GetInvocationList();
}
// Also searches up the inheritance hierarchy
private static FieldInfo GetStaticNonPublicFieldInfo(Type type, string name)
{
FieldInfo fi;
do
{
fi = type.GetField(name, BindingFlags.Static | BindingFlags.NonPublic);
type = type.BaseType;
} while (fi == null && type != null);
return fi;
}
和
public static List<Delegate> RetrieveAllAttachedEventHandlers(Control c)
{
List<Delegate> result = new List<Delegate>();
foreach (EventInfo ei in c.GetType().GetEvents())
{
var handlers = RetrieveControlEventHandlers(c, ei.Name);
if (handlers != null) // Does it have any attached handler?
result.AddRange(handlers);
}
return result;
}
最後一個方法將提取所有連接到控制事件的事件處理程序。這包括來自所有類的處理程序(甚至由winforms內部附加)。您也可以通過處理器的目標對象篩選列表:
public static List<Delegate> RetrieveAllAttachedEventHandlersInObject(Control c, object handlerContainerObject)
{
return RetrieveAllAttachedEventHandlers(c).Where(d => d.Target == handlerContainerObject).ToList();
}
現在你可以在formB
定義gridControl1
所有的事件處理程序:
RetrieveAllAttachedEventHandlersInObject(gridControl1, formB);
這可能會幫助您:HTTP:// stackoverflow.com/questions/91778/how-to-remove-all-event-handlers-from-a-control – Anuraj 2013-03-26 05:37:32