#591 – You Can Attach Any Routed Event to Any Control

When you attach an event handler to a control, you most typically attach a handler for an event that is defined for that control.  For example, the Button control has a Click event defined.

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

In WPF, however, you can actually attach any routed event to any control–whether or not that control defines the event or not.  For example, we can attach a handler for the Click event to a StackPanel object, using the full name for the ButtonBase.Click event.

A control won’t normally fire events that it doesn’t define, except that when events are routed, they can fire on every control higher up (or down) in the logical tree.

    <StackPanel ButtonBase.Click="StackPanel_Click">
        <Button Content="Like" Click="Button_Click"/>
    </StackPanel>

Now, when you click on the Button, both handlers that you define will see the Click event, because it bubbles up the logical tree.

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #591 – You Can Attach Any Routed Event to Any Control

  1. Pingback: #1,073 – Attached Events | 2,000 Things You Should Know About WPF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: