Compartilhar via


Como: usar anexadas eventos

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"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="300" Width="300" Button.Click="myHandler">
        <Grid>
            <Button Height="23" HorizontalAlignment="Left"
            Margin="33,38,0,0" Name="Button1" VerticalAlignment="Top" 
            Width="75">Button</Button>
        </Grid>
    </Window>
    

    Neste exemplo, o manipulador de evento para o Button.Click evento é criado na Window definição com o código de 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.

Consulte também

Tarefas

How to: Create a Simple Event Handler

Como: Usar Propriedades Afeiçoadas

Conceitos

Visão geral do XAML (WPF)

Visão geral sobre eventos roteados