Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
947 views
in Technique[技术] by (71.8m points)

wpf - Difference between Bubbling and Tunneling events

What is the exact difference between Bubbling Events and Tunneling events? Where should I use Bubbling Events and where should I use Tunneling events? Thanks in Advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

WPF gives us a number of different mechanisms for handling events – they are bubbling, tunneling, and direct. These are all known as Routed events.

Direct event

You are probably already used to the direct routed event. This is where the item itself handles the event that occurred. A good example would be handling he onClick-event of a mouse button in standard WinForms. This is where the event is raised in the GUI item and gets handled by said GUI element.

Bubbling Event

Now we all like some bubbles in one form or another. Bubbling happens when the event is not handled by the element ( say a textbox) and the event "bubbles" its way up the UI containers which hold it. For example, let's say you have a window that contains a panel and inside that panel you have a grid and inside the grid you have a textbox. If the event is not handled by the textbox, then it moves, is passed or "bubbles" up to the grid level (as the grid contains the textbox), if it is not handled at that level then the event bubbles further up the "tree" (known as a visual tree) to the panel where it may or may not be handled. This process continues until it is handled or the event "escapes" the top most element.

Examples of a bubbling event would be something like a MouseButtonDown event. Or a Keydown event.

Tunneling

Tunneling is the opposite of Bubbling. So instead of an event going "up" the visual tree, the event travels down the visual tree toward the element that is considered the source. The standard WPF naming definition of a tunneling event is that they all start with "preview" for example previewdownkey and previewmousebuttondown. You can catch them on their way to the "target" element and handle it. An example for this might be perhaps you have some controls inside a grid control and for some reason you have decided that no control within that grid will be allowed to have the letter "t" reach it.

Source with the opinion of the author which I don't support nor agree with.

And another StackOverflow question which is pretty much the same.

A nice demo project

And last but not least some explanation and another tutorial.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...