Event Handling


WPF classes define events where you can add your handlers; for example, MouseEnter, MouseLeave, MouseMove, Click, and the like. This is based on the events and delegates mechanism on .NET.

Tip 

You can read the event and delegate architecture of .NET in Chapter 7, “Delegates and Events.”

With WPF, you can assign the event handler either with XAML or in the code behind. With button1 the XML attribute Click is used to assign the method OnButtonClick to the click event. button2 has no event handler assigned in XAML:

  <Button Name="button1" Click="OnButtonClick">Button 1</Button> <Button Name="button2" Button 2</Button> 

The Click event for button2 is assigned in the code behind by creating an instance of the delegate RoutedEventHandler and passing the method OnButtonClick to the delegate. The method OnButtonClick() that is invoked from both buttons has arguments as defined by the RoutedEventHandler delegate:

  public Window1() {    InitializeComponent();    button2.Click += new RoutedEventHandler(OnButtonClick); } void OnButtonClick(object sender, RoutedEventArgs e) {    MessageBox.Show("Click Event"); } 

The event-handling mechanism for WPF is based on .NET events but extended with bubbling and tunneling features. As you’ve already learned, a Button can contain graphics, list boxes, another button, and so on. What happens if a CheckBox is contained inside a Button and you click the CheckBox? Where should the event arrive? The answer is that the event is bubbled. First, the Click event arrives with the CheckBox, and it then bubbles up to the Button. This way you can handle the Click event for all elements that are inside the Button with the Button.

Some events are tunneling events; others are bubbling events. A tunneling event first arrives with the outer element and tunnels to the inner elements. Bubbling events start with the inner element and bubble to the outer elements. Tunneling and bubbling events usually are paired. Tunneling events are prefixed with Preview, for example, PreviewMouseMove. This event tunnels from the outer controls to the inner controls. After the PreviewMouseMove event, the MouseMove event occurs. This event is a bubbling event that goes from the inner to the outer controls.

You can stop tunneling and bubbling by setting the Handled property of the event argument to true. The Handled property is a member of the RoutedEventArgs class, and all event handlers that participate with the tunneling and bubbling facility have an event argument of type RoutedEventArgs or a type that derives from RoutedEventArgs.

Tip 

If you stop the tunneling of an event by setting the Handled property to true, the bubbling event that follows the tunneling event will not happen anymore.




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net