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

前端 未结 2 696
轻奢々
轻奢々 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.)

提交回复
热议问题