Creating Event Handlers for WPF Controls
In this lesson, you will learn how to create an event handler for a WPF control.
You can add the default event handler for many controls by double-clicking the control in Design view. You can also create event handlers for controls that you add to a Windows Presentation Foundation (WPF) application by using a combination of XAML and Visual Basic code. First, you define the event and the name of the method that will handle the event in an attribute of the control in the XAML editor. Then you can add the event handler code in the Code Editor.
To create an event handler for a button
Create a WPF application in Visual Basic Express. For more information, see How to: Create a New WPF Application Project.
Drag a Button from the Toolbox to the WPF design surface, and then select the button.
Double-click the button.
The Button1_Click event handler is created and the mouse cursor is placed inside the event handler in the Code Editor.
Add the following code to the event handler. This code displays a message when you click the button.
MsgBox("Event handler was created by double-clicking the button.")
Switch back to Design view, drag a second Button from the Toolbox to the WPF design surface, and then select the button.
In the XAML editor, which is located below the design area, find the button that has its Name attribute set to Button2. In this code, after <Button, type Click="Button2_Click" to specify the event handler. The line in the XAML editor should start as follows:
Right-click the design surface and click View Code.
Add the following event handler to the Window1 class.
Sub Button2_Click(ByVal Sender As Object, ByVal e As RoutedEventArgs) End Sub
Add the following code in the Button2_Click method.
MsgBox("Event handler was created manually.")
You can see that the Button1_Click event handler has the Handles clause, while Button2_Click does not. This is because when you create an event handler by double-clicking the control, as you did with the first button, the Click attribute is not added to the XAML markup. Instead, the Handles clause is used to hook up the event with the event handler.
Press F5 to run the program.
When the window appears, click the button.
Verify that the correct text appears in a message box when you click each button, and then close the application.
In this lesson, you learned how to create an event handler for a Button control.
In the next lesson, you will learn how to create a WPF application that enables you to draw pictures.
Next Lesson: Creating a Drawing Application by Using WPF.