How to: Use Attached Events
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
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="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://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>
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.
In the code-behind file, add your code to the event handler.