What are routed events and how it's different from normal events

前端 未结 2 681
轻奢々
轻奢々 2020-12-17 15:55

I will appreciate if some body can explain with a simple example.

相关标签:
2条回答
  • 2020-12-17 16:27

    Imagine a Window containing a dense hierarchy of child controls. Now let's say you want to do something, there's a right click anywhere in your window.

    • With normal events, you'd have to handle a Click event for all controls, because you're not sure where the user might click.
    • With WPF's routed events, the events either "bubble" or "tunnel" (i.e travel up the UI tree or down) if they dont find an event handler, which "handles" it at the current level. So you could write one handler for the window's event i.e. TopLevel. (WPF has a convention of event pairs, PreviewXXX and XXX - the PreviewXXX event fires first and tunnels down from root to control which received the stimulus and the counterpart XXX event then bubbles up from child control back upto Root). So if you right click a button, WPF travels up the UI hierarchy, invoking all handlers that it finds (unless someone marks the event has "handled" in the event args.)
    0 讨论(0)
  • 2020-12-17 16:30

    Routed events are events with more 'traveling abilities', as mentioned in a Gishu's answer. Routed events are represented by an instance of a RoutedEvent class + ordinary .NET event, which wraps it:

        public class MyClassWithARoutedEvent : UIElement
        {
            public static readonly RoutedEvent DoSomethingEvent;
    
            public event RoutedEventHandler DoSomething
            {
                add { base.AddHandler ( MyClassWithARoutedEvent.DoSomethingEvent, value );
                remove { base.AddHandler ( MyClassWithARoutedEvent.DoSomethingEvent, value );
            }
       }
    

    You would typically use touted events in such situations:

    • Implementing your own control which seamlessly integrates with WPF's infrastructure
    • Processing events, fired by different controls at a common root
    • Sort of communication between elements in an element tree In most situations you will probably use the routed events infrastructure without even noticing it.

    In addition it's worth to mention, that you can use RoutedEvent in your control even if it does not define it or even inherits from an element, which does. That's because you can really think about a RoutedEvent instance as a strong typed name of an event. So, if you have an access to this 'name' (this is why an instance of a routed event is usually made public), you can owe it:

    public class MyClassWithARoutedEvent : UIElement
        {
            public static readonly RoutedEvent ClickEvent;
            static MyClassWithARoutedEvent  ( )
            {
              ClickEvent = ButtonBase.ClickEvent.AddOwner( typeof ( MyClassWithARoutedEvent ) );
            }
    
           // A wrapper should be placed here as described above
        }
    
    0 讨论(0)
提交回复
热议问题