7

我想在一次调用中挂钩所有可用的元素事件。像这样的一些事情:

elem.AddHandler(AnyRoutedEvent, (RoutedEventHandler)handler)

我怎样才能做到这一点?

4

3 回答 3

10

试试这个来获取 Button 类型的所有事件......您可以替换不同的类型。

RoutedEvent[] events = EventManager.GetRoutedEventsForOwner(typeof(Button));

foreach (RoutedEvent e in events)
   elem.AddHandler(e, handler);

您还可以替换以下内容以获取所有类型的所有路由事件,但这将是一个相当多的列表!

RoutedEvent[] events = EventManager.GetRoutedEvents();
于 2009-03-11T13:20:47.617 回答
4

您可以使用 EventManager 的 RegisterClassHandler 方法一次静态监听所有元素 :)

EventManager.RegisterClassHandler(typeof(your class), Button.ClickEvent, new RoutedEventHandler(OnButtonClick));

static void OnButtonClick(object sender, RoutedEventArgs e)
{
    //Do awesome stuff with the button click
}
于 2009-03-11T13:28:55.523 回答
1

我的灵感来自: http: //geekswithblogs.net/tkokke/archive/2009/07/17/monitoring-routed-events-in-wpf.aspx

    /// <summary>
    /// This is used for debugging, when your looking for a specific event
    /// </summary>
    public static void RegisterAllEvents(Type type, FrameworkElement target)
    {
        var events = EventManager.GetRoutedEvents();
        foreach (var routedEvent in events)
        {
            EventManager.RegisterClassHandler(type,
                                routedEvent, new RoutedEventHandler((sender, args) =>
                {
                    if ( sender != target)
                        return;
                    System.Diagnostics.Debug.WriteLine(args.OriginalSource + "=>" + args.RoutedEvent);
                }));
        }
    }
于 2017-09-18T16:06:41.903 回答