#659 – Detecting a Triple Click

Although not very common in user interfaces, you can use the MouseButtonEventArgs.ClickCount property, available in the PreviewMouseDown or MouseDown events, to detect a triple click.  (You can also detect right vs. left mouse button clicks using the button specific events, e.g. MouseLeftButtonDown and MouseRightButtonDown).

In the example below, double clicking on the Label does nothing.  But a triple click, with either button, toggles the background color of the label.

    <StackPanel Margin="20" >
        <Label Content="Triple-click on me" Margin="20"
               MouseDown="Label_MouseDown" />
    </StackPanel>

In the event handler, we check ClickCount and change the Background of the Label if it’s equal to 3 (a triple click).

        private bool colorToggled = false;

        private void Label_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 3)
            {
                if (!colorToggled)
                {
                    ((Label)sender).Background = Brushes.Blue;
                    colorToggled = true;
                }
                else
                {
                    colorToggled = false;
                    ((Label)sender).Background = null;
                }
            }
        }


Advertisements