问题描述
我需要给一个对象分配一个eventHandler,这样:
I need to assign an eventHandler to an object, in this way:
_Element.AddHandler(UIElement.MouseLeftButtonUpEvent,
new RoutedEventHandler(Vars.Digit), true);
但事实上,我在 Vars 对象实例中只有一个包含Digit"或其他方法名称的字符串.
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?
谢谢.
推荐答案
是的,你可以找到 Type.GetMethod
,以及带有 Type.GetEvent
,然后使用 EventInfo.AddEventHandler
.这可能有点繁琐——而且会有很多地方可以进行错误处理——但应该不会太难.如果您希望能够绑定非公共方法/事件,请不要忘记指定绑定标志.
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.
这篇关于在字符串中动态添加具有委托名称的事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!