WPF Concepts—Routing Strategies and Event Handlers
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:Articles |
| .NET Articles |
|
| © 2007 Sams Publishing |
Routing Strategies and Event Handlers
When registered, every routed event chooses one of three routing strategies—the way in which the event raising travels through the element tree. These strategies are exposed as values of a RoutingStrategy enumeration:
-
Tunneling—The event is first raised on the root, then on each element down the tree until the source element is reached (or until a handler halts the tunneling by marking the event as handled).
-
-
Bubbling—The event is first raised on the source element, then on each element up the tree until the root is reached (or until a handler halts the bubbling by marking the event as handled).
-
-
Direct—The event is only raised on the source element. This is the same behavior as a plain .NET event, except that such events can still participate in mechanisms specific to routed events such as event triggers.
-
Handlers for routed events have a signature matching the pattern for general .NET event handlers: The first parameter is a System.Object typically named sender, and the second parameter (typically named e) is a class that derives from System.EventArgs. The sender parameter passed to a handler is always the element to which the handler was attached. The e parameter is (or derives from) an instance of RoutedEventArgs, a subclass of EventArgs that exposes four useful properties:
-
Source—The element in the logical tree that originally raised the event.
-
-
OriginalSource—The element in the visual tree that originally raised the event (for example, theTextBlockorButtonChromechild of a standardButton).
-
-
Handled—A Boolean that can be set totrueto mark the event as handled. This is precisely what halts any tunneling or bubbling.
-
-
RoutedEvent—The actual routed event object (such asButton.ClickEvent), which can be helpful for identifying the raised event when the same handler is used for multiple routed events.
-
The presence of both Source and OriginalSource enable you to work with the higher-level logical tree or the lower-level visual tree. This distinction only applies to physical events like mouse events, however. For more abstract events that don't necessarily have a direct relationship with an element in the visual tree (like Click due to its keyboard support), the same object is passed for both Source and OriginalSource.
|

