views:

94

answers:

1

Hi!

I need to assign an eventHandler to an object, in this way:

_Element.AddHandler(UIElement.MouseLeftButtonUpEvent, new RoutedEventHandler(Vars.Digit), true);

but, in fact, I only have a string that contains "Digit" or other method name in the Vars object instance.

It is possible to achieve this using reflection or other kind of trick?

Thanks.

A: 

Yes, you can find the method with Type.GetMethod, and the event with Type.GetEvent, then add a handler with EventInfo.AddEventHandler. It may be slightly fiddly - and there'll be a lot of places to put error handling - but it shouldn't be too hard. Don't forget to specify binding flags if you want to be able to bind non-public methods/events.

Jon Skeet
Thanks, but having the instance of an object(Vars in the snippet), how can I tell to the _Element.AddHandler that point at the method named "Digit" of this specific object? Thanks Again Jon.
Jonathan
Use `Vars.GetType()` to get the type containing the method you want to add a handler for, and `_Element.GetType()` to find the type containing the event. `AddEventHandler` takes an object which is the "target" of the delegate - in your case this would be `Vars`.
Jon Skeet