Ignacio Soler Garcia
Ignacio Soler Garcia

Reputation: 21855

Why I cannot handle a EventHandler<XXX> with an EventHandler?

I have the following code trying to attach a generic event handler at run time:

EventInfo info = source.GetType().GetEvent("EventWithArgsInheritingFromEventArg");
info.AddEventHandler(source, new EventHandler((obj, args) => DoSomething()));

When I try to do that I get the following Exception:

Object of type 'System.EventHandler' cannot be converted to type 'System.Windows.Controls.DataGridSortingEventHandler'.

It's my understanding that a method with a signature (object sender, EventArgs e) can handle any event with a parameter inheriting from EventArgs right?

What's wrong with my approach?

Thanks

EDIT: Can this make any difference? Could it happen that DaraGridSortingEventHandler does not inherit from EventHandler???

enter image description here

Upvotes: 1

Views: 337

Answers (1)

sloth
sloth

Reputation: 101032

You can not use different delegates using the AddEventHandler method, but a workaround is to create a delegate using Delegate.CreateDelegate first:

EventInfo info = source.GetType().GetEvent("EventWithArgsInheritingFromEventArg");

// create the event handler
var eventhandler = new EventHandler(this.DoSomething);

// create a delegate from the EventHandler
var @delegate = Delegate.CreateDelegate(info.EventHandlerType, null, eventhandler.Method);

info.AddEventHandler(source, @delegate);

Upvotes: 1

Related Questions