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

  1. Create a WPF application by using Visual C# Express Edition. For more information, see How to: Create a New WPF Application Project.

  2. Drag a Button from the Toolbox to the WPF window, and then select the button.

  3. Double-click the button.

    The Click event handler is created and the cursor is positioned in the event handler in the Code Editor.

  4. Add the following code to the event handler:

    MessageBox.Show("Event handler was created by " +
         "double-clicking the button.");
    
  5. Drag a second Button control from the Toolbox to the WPF design surface, and then select the button.

  6. 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".

  7. Right-click the designer and then click View Code.

  8. 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."); 
    }
    
  9. Press F5 to run the program.

  10. When the window appears, click a button.

  11. 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

How to: Use Attached Events

Concepts

Common WPF Controls

Other Resources

Getting Started with the WPF Designer