How to: Create Event Handlers for WPF Controls
You can add the default event handler for many controls by double-clicking the control in Design view. You can also create an event handler for controls in a Windows Presentation Foundation (WPF) application by adding an attribute to the control's XAML representation. This XAML markup defines the event and the name of the method that will handle the event. Then, you write the code for the method in the Code Editor.
To create an event handler for a button
Create a WPF application by using Visual C# Express Edition. For more information, see How to: Create a New WPF Application Project.
Drag a Button from the Toolbox to the WPF window, and then select the button.
Double-click the button.
The Click event handler is created and the cursor is positioned in the event handler in the Code Editor.
Add the following code to the event handler:
MessageBox.Show("Event handler was created by " + "double-clicking the button.");
Drag a second Button control from the Toolbox to the WPF design surface, and then select the button.
Add an attribute named Click to the Button element in the XAML editor, and set its value to ButtonOKClicked. This is the name that you will give the event handler in code. For example, the attribute can be written as follows: Click="ButtonOKClicked".
Right-click the designer and then click View Code.
Add the following event handler to the Window1 class. This code displays a message whenever you click the button.
private void ButtonOKClicked(object sender, RoutedEventArgs e) { MessageBox.Show("Event handler was created manually."); }
Press F5 to run the program.
When the window appears, click a button.
Verify that the correct text appears in a message box when you click each button, and then close the application.
See Also
Tasks
How to: Add New Items to a WPF Project
Designing a User Interface for a WPF Application