Handling Events in WPF

You handle events in WPF the same way you do in other kinds of applications: You code a Visual Basic event handler and associate the handler to a control event. What actually changes is the way you assign the handler to the event. For example you can assign an event handler to a control event directly within the XAML code editor. To accomplish this you simply type the name of the event you want to handle (events are recognizable within IntelliSense with the Lightning icon) and then press Tab when IntelliSense shows the <New Event Handler> pop-up command (see Figure 31.11 for details).

Figure 31.11 Generating a new event handler with IntelliSense.

image

This generates an event handler stub in your code-behind file. Continuing the example of the previous button, Visual Studio first assigns a new identifier to the Click event in XAML, which looks like this:

Click="Button1_Click"

As you can see, the IDE generates the event handler’s identifier considering the control’s name. Now right-click the event handler’s name and select the Navigate to Event Handler command from the pop-up menu. This redirects to the Visual Basic event handler generated for you, which looks like this:

image

It is worth mentioning two aspects. The first one is that the event handler signature requires an e argument of type RoutedEventArgs. WPF introduces the concept of routed events that is covered in the next section. The second one is that in this case there is no Handles clause. This is because the IDE added an AddHandler instruction behind the scenes in the Window1.g.vb file (which is generated at compile time). Notice that such a file name depends on the current Window name, in this case Window1. As an alternative you can specify the Handles clause the same way you would do in other kinds of applications, but in this case you must not specify the event handler in XAML, to avoid an event being caught twice. You can also double-click a control in the designer to generate an event handler for the default event. For example, a button’s default event is Click, so double-clicking a button in the designer generates an event handler stub for handling the Click event. The default event for a TextBox control is TextChanged, so double-clicking a text box generates an event handler stub for the TextChanged event, and so on. When you add event handlers by double-clicking controls, such handlers use the Handles clause on the method name. As previously mentioned, the last alternative is to assign an existing event handler to a control’s event with the Properties window.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.25.112