#1,074 – Attached Event Syntax

Attached events allow attaching a handler for an event that is defined in an element other than the one adding the handler.  For example, a StackPanel might define a handler for the Click event that is defined in ButtonBase.

When defining handlers in XAML, the event name is used by itself if that event is defined for the element raising the event.

        <Button Content="Click Me" Click="Button_Click"/>

When defining a handler on an element that does not define the handler’s event, you prefix the event name with the name of the class that defines the event.

    <StackPanel Button.Click="StackPanel_Button_Click">
Advertisements

#1,073 – Attached Events

When events are routed in WPF, elements up (bubbling) or down (tunneling) the logical tree are given the chance to add a handler for a particular event.

For example, if you have a Button within a StackPanel and the user clicks on the Button, the Button will raise a Click event, but also bubble the event up to the StackPanel so that it can also raise the Click event.

Click is defined as a RoutedEventHandler in the ButtonBase class.  There is also a public static ClickEvent object of type RoutedEvent defined in ButtonBase.  So we think of ButtonBase as “owning” the Click event.  This makes sense, since buttons are generally the elements that will raise Click events.

The StackPanel does not define a Click event, but can define a handler for a routed event object that it does not own.  This is known as an attached event.