Search code examples
.netwpftreetunneling

WPF Tunneling, practical use?


What practical scenarios need to use Tunneling of events?

I know a vague answer to this could be that it is used when we want to handle a event across the visual/logical on which event is raised. But that's just theory.

In practice why should I tunnel an event?

Also does tunneling (and bubbling) works across Logical tree or Visual tree or both?


Solution

  • I find tunneling events to be very useful for handling events on elements which I have not created myself, and hence have no easy way to add an event handler to. For example, the ItemsControl generates UI elements based on a template, as a result it is not always a straightforward process to get a reference to these elements. Rather than adding an event handler to each item which the ItemsControl generates you can instead handle the tunnelled event on a single parent element.

    Routed events traverse a 'hybrid' tree, which is neither the visual or logical tree. This sounds a bit crazy, but it has never cause me problems in the past.