Site Logo

Pixel-in-Gene

Exploring Frontend Development with Design / Graphics / Technology

Attached events

We are all well aware of the Attached properties concept and have definitely used it a lot. But on a similar tone there is also the concept of Attached Events, which are useful in some particular cases.

Imagine you have a set of Buttons contained inside a WrapPanel.

<WrapPanel Button.Click="CommonHandler">
    <Button x:Name="btn1"
                    Content="Click me"/>
    <Button x:Name="btn2"
                    Content="Click me"/>
    <Button x:Name="btn3"
                    Content="Click me"/>
    <TextBlock x:Name="_statusText"/>
</WrapPanel>

Now I want my application to react to the button clicks. You could either set the Click events of all the buttons to point to separate event handlers or you could make them point to the same handler. One other approach is to use attached events. Note how I specify Button.Click on my WrapPanel. This is possible because the Click event is registered on the Button class as a static RoutedEvent. Since the event is set to bubble up, it will get handled at the WrapPanel stage (ie sender = WrapPanel).

Attached events are very useful in scenarios where you have a more complex UI hierarchy and you would like a common handler for some set of events. Instead of doing it specifically for that control, you can associate it at a much higher level. It may also be an alternative to the PreviewXXX events, which go top-down instead of bottom-up (Bubbled events).

I have found attached events useful for MenuItems. Instead of short-circuiting the Click handler for each of the MenuItems I set the handler at the ContextMenu/Menu as MenuItem.Click. It also gives you slightly cleaner XAML.

[EDIT] I found this great article at SerialSeb which discusses Attached Events with greater detail.

Attached events
Pavan Podila
Pavan Podila
February 6th, 2007