【问题标题】:GetEvent() returns null for attached eventGetEvent() 为附加事件返回 null
【发布时间】:2011-09-28 00:49:13
【问题描述】:

当我尝试获取 WPF 'rectangle' 的 eventinfo 时,如果 routedEvent 是对象的本机事件(例如 'MouseDown'),它会起作用(分配仅作为示例)。

DependencyObject d = rectangle;
string routedEvent = "MouseDown";

EventInfo eventInfo = d.GetType().GetEvent(routedEvent, 
                BindingFlags.Public | BindingFlags.Instance);

但是当我想在矩形上获取附加事件的 EventInfo(我认为我正确使用了该术语)时,例如:

string routedEvent = "Microsoft.Surface.Presentation.Contacts.ContactDownEvent"; 

GetEvent() 返回 null

关于如何获取附加事件的事件信息的任何想法。

谢谢

【问题讨论】:

    标签: wpf events reflection


    【解决方案1】:

    您可能想要使用更具体的EventManager.GetRoutedEventsForOwner 方法。

    我相信 MSDN 文档说的不正确:

    基类包含在 搜索。

    这是证据:

    Debug.Assert(EventManager.GetRoutedEventsForOwner(typeof(Rectangle)) == null);
    Debug.Assert(EventManager.GetRoutedEventsForOwner(typeof(Shape)) == null);
    //even though FrameworkElement is a base class of the above!
    Debug.Assert(EventManager.GetRoutedEventsForOwner(typeof(FrameworkElement)) != null);
    

    因此,您可能需要自己爬取类型层次结构,或者如果它是一次性的,只需传入typeof(FrameworkElement)typeof(Rectangle)

    【讨论】:

    • RoutedEvent[] routedEvents = EventManager.GetRoutedEventsForOwner(d.GetType());返回空?我验证了 d.GetType() 返回矩形。
    • 肯特,感谢您的建议。我觉得我越来越近了。我最初的请求是获取 EventInfo 对象,因为我想添加一个事件处理程序(通过 .AddEventHandler)。如果我得到一个 RoutedEvent 类型而不是 EventInfo(通过您的建议),我该如何添加一个处理程序?谢谢
    • @Dan 我面临着和你一样的情况。您找到解决 EventInfo 和 RoutedEvent 问题的方法了吗?
    【解决方案2】:

    因为附加事件不会作为常规 C# 事件公开。在Mouse 类中,没有这样的东西:

    public event MouseButtonEventHandler MouseDown;
    

    相反,有一个 MouseDownEvent 类型为 RoutedEvent 的静态字段:

    public static readonly RoutedEvent MouseDownEvent;
    

    您使用EventManager 订阅/取消订阅该事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-14
      相关资源
      最近更新 更多