Add event handler dynamically having the delegate name in a string

谁说胖子不能爱 提交于 2019-12-17 16:53:25

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/1900302/add-event-handler-dynamically-having-the-delegate-name-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!