This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Base Classes - Control - Double-Clicking

The thirty-first part of the Windows Presentation Foundation Fundamentals tutorial brings the examination of the Control class to a close. This article describes an event defined within the class that detects double-clicking.


Over the past three articles we've looked at the Control class, which is a base class for many of the WPF controls that we've seen earlier in this tutorial and for some that we'll be seeing later. We started the examination of Control by seeing how the tab order is generated and manipulated. Next we looked at font options, then some miscellaneous visual properties. In this article we'll look at an event before moving on to other base classes. We'll return to the Control class later in the tutorial when discussing control templates.

Control defines events that allow you to detect when a control is double-clicked. One of these is MouseDoubleClick. This routed event is raised by the control that is initially double-clicked before bubbling up the logical tree, potentially firing for all parent controls.

We can demonstrate the event with a simple example. Create a new WPF Application project in Visual Studio, naming it, "ControlMouseDoubleClick". Replace the XAML of the main window with the code shown below:

<Window x:Class="ControlMouseDoubleClick.MainWindow"
        Title="Control Demo"
    <Expander Name="MyExpander"
              Header="Double-Click Anywhere"
        <Label HorizontalAlignment="Center" VerticalAlignment="Center">Hello, World</Label>

The above XAML defines an Expander control that contains a Label. The Expander handles the MouseDoubleClick event, for which we need some code behind the window. Switch to the code and add the following method to handle the event:

private void MyExpander_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    MyExpander.IsExpanded = !MyExpander.IsExpanded;

This simple code detects double-clicks. When a double-click occurs, the Expander is expanded or collapsed. Try running the program to see the results. As the Expander fills the window you should find that you can double-click anywhere in the window's area to toggle the expansion. Single-clicking to expand and collapse the control only works when you click within the header area.

NB: The event passes a MouseButtonEventArgs instance that permits you to understand which button was used and the co-ordinates of the mouse pointer when the event was triggered. You can also use the event arguments to cancel routing of the event. These event arguments are described in the article, "WPF Base Classes - UIElement - Mouse Events".

10 October 2013