Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add listener for all element events in WPF

I would like to hook for all available element events in one call. Some thing like this:

elem.AddHandler(AnyRoutedEvent, (RoutedEventHandler)handler)

How can I do this?

like image 985
alex2k8 Avatar asked Mar 11 '09 13:03

alex2k8


3 Answers

Try this to get all events on the Button type... You can substitute a different type.

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

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

You can also substitute the following to get ALL routed events for ALL types, but that would be quite a list!

RoutedEvent[] events = EventManager.GetRoutedEvents();
like image 189
Josh G Avatar answered Nov 20 '22 14:11

Josh G


You can use the RegisterClassHandler method of EventManager to staticly listen to all elements at once :)

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

static void OnButtonClick(object sender, RoutedEventArgs e)
{
    //Do awesome stuff with the button click
}
like image 21
Arcturus Avatar answered Nov 20 '22 13:11

Arcturus


I created this from inspiration from: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);
                }));
        }
    }
like image 22
RJ Thompson Avatar answered Nov 20 '22 12:11

RJ Thompson