How to: Use Attached Events

[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]

Elements can respond to events raised by other elements in the XAML tree, even if they do not define those events themselves. For example, a Window that contains a Button control can respond to the Click event raised by that Button, even though Window does not define a Click event itself. This is accomplished by specifying a handler for the Button.Click (or ButtonBase.Click) event in the Window definition. This handler will be executed whenever a Button (or any control that inherits from ButtonBase) in the window's XAML tree is clicked. The following procedure and example demonstrates how to use attached events.

To use an attached event

  1. In an element, specify an event handler for an attached event that you want to handle. For more information, see How to: Create a Simple Event Handler.

    The following XAML shows how to specify an event handler for the Button.Click event in a Window.

                  <Window x:Class="MainWindow"
    Title="MainWindow" Height="300" Width="300" Button.Click="myHandler">
            <Button Height="23" HorizontalAlignment="Left"
            Margin="33,38,0,0" Name="Button1" VerticalAlignment="Top" 

    In this example, the event handler for the Button.Click event is created in the Window definition with the code Button.Click="myHandler". This method will be executed whenever any button in the window's tree is clicked.

  2. In the code-behind file, add your code to the event handler.