#581 – An Example of a Routed Event

In WPF, events that fire as a result of interacting with user interface elements are routed up or down a tree of user interface elements.

In the example below, we’ve attached a handler for the KeyDown event to the first TextBox control.  We also define handlers for the StackPanel that contains this TextBox, as well as the higher level StackPanel and the main Window.

Displaying a message from within each of these event handlers, we see the following output when we move focus to the TextBox and then press a key.

Four events are fired, starting in the TextBox and then preceding up the logical tree.  The event travels up the tree because KeyDown is a bubbling event–it “bubbles up” the logical tree.

In each handler, e.Source refers to control where the event originated and Sender refers to the control that owns the handler.