Routed Events

The standard way that .NET classes and controls raise and handle events is essentially the way that you perform these tasks in WPF. But the WPF libraries bring an important improvement to standard events. We call these routed events.

Consider a simple scenario. You have a Button control that consists of a background image and some text (see Figure 21.22). If you recall from our discussion of a controls template and visual tree, this means we actually have a few discrete elements that make up the button: a TextBlock, an Image, and the basic frame and background of the button.

Image

FIGURE 21.22 A button made of multiple elements.

These are separate objects/elements unto themselves. So the event situation becomes a little complex. It isn’t enough to react to a click on the button background; we also have to react to a click on the button’s text or the button’s image. This is where routed events come into play. Routed events are capable of calling event handlers up or down the entire visual tree. This means we are free to implement an event handler at the Button level and be confident that a click on the button’s image or text will bubble up until it finds our event handler.

Routed events in WPF are broken down into three categories: bubbling events, tunneling events, and direct events:

Image Bubbling events—These events travel up the visual tree starting at the initial receiving element.

Image Tunneling events—These events start at the top of the control’s visual tree and move down until they reach the receiving element.

Image Direct event—These are the equivalent of “standard” .NET events: Only the event handler for the receiving element is called.

Events themselves, like nearly everything else in WPF, can be declared in XAML or in code. Here we have a Button control with a MouseEnter event defined.

<Button MouseEnter="button1_MouseEnter" Name="button1"
>OK</Button>

The event handler itself, in C#, looks like any other .NET event handler.

private void button1_MouseEnter(object sender, MouseEventArgs e)
{
   MessageBox.Show("MouseEnter on button1");
}

We have only scratched the surface on many of the basic programming concepts within WPF, but you should now be armed with enough knowledge to be productive writing a simple WPF application. Let’s do just that, using the tools available to us in Visual Studio.

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

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