I am trying to subscribe to ALL events exposed by a WPF GridView-like 3rd party component in order to do some debugging. Aside from the suggestion that this might not be the best way to go about debugging it and stuff like that I would like to know if this can be done.
For the routed events it worked ok like this :
var type = tree.GetType();
do
{
var staticFields = type.GetFields(BindingFlags.Static | BindingFlags.Public);
foreach (var staticField in staticFields)
{
if (typeof(RoutedEvent).IsAssignableFrom(staticField.FieldType))
{
tree.AddHandler((RoutedEvent)staticField.GetValue(null), new RoutedEventHandler(OnRoutedEvent), true);
}
}
} while ((type = type.BaseType) != typeof(object)/* && type.FullName.StartsWith("Telerik")*/);
public void OnRoutedEvent(object sender, System.Windows.RoutedEventArgs e)
{
Debug.WriteLine(e.RoutedEvent.ToString());
}
However, with typical events this doesn't seem to work :
var evts = tree.GetType().GetEvents();
foreach (var ev in evts)
{
ev.AddEventHandler(this, new EventHandler(OnEvent));
}
public void OnEvent(object sender, EventArgs e)
{
//..
}
because it doesn't like either the thing that the delegate is EventHandler instead of the specialized type or because the signature of the event handler method does not contain the specialized EventArgs class type.
Can this be done somehow?
------------ LATER EDIT --------- In all three cases (my attempt, ds27680's suggestion and Thomas Levesque's suggestion) the AddEventHandler call fails with :
System.Reflection.TargetException occurred
Message=Object does not match target type.
Source=mscorlib
StackTrace:
at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.EventInfo.AddEventHandler(Object target, Delegate handler)
at Test.MainWindow..ctor() in c:\users\me\documents\visual studio 2010\Projects\Test\Test\MainWindow.xaml.cs:line 39
I guess the fact that the event handler method's signature does not match EXACTLY the EventArgs type is what makes it fail...