Wednesday, April 13, 2011

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?

From stackoverflow
  • 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();
    
  • 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
    }
    

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.