views:

465

answers:

3

I can catch a single-click on a TextBlock like this:

private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
    MessageBox.Show("you single-clicked");
}

I can catch a double-click on a TextBlock like this:

private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (e.LeftButton == MouseButtonState.Pressed)
    {
        if (e.ClickCount == 2)
        {
            MessageBox.Show("you double-clicked");
        }
    }
}

But how do I catch them both on a single TextBlock and differentiate between the two?

+2  A: 

If you need to detect the difference, I suggest you use a control such as Label that does the work for you:

label.MouseDown += delegate(object sender, MouseEventArgs e)
{
    if (e.ClickCount == 1)
    {
        // single click
    }
};

label.MouseDoubleClick += delegate
{
    // double click
};

EDIT: My advice was following from documentation on MSDN:

The Control class defines the PreviewMouseDoubleClick and MouseDoubleClick events, but not corresponding single-click events. To see if the user has clicked the control once, handle the MouseDown event (or one of its counterparts) and check whether the ClickCount property value is 1.

However, doing so will give you a single click notification even if the user single clicks.

HTH,
Kent

Kent Boogaart
+1 for suggestion to use label, didn't realize it inherited from Control unlike TextBlock, but actually in my application I am receiving a FrameworkElement so I need some solution without using Control.
Edward Tanguay
A: 

Simply check for ClickCount == 1...

Example from MSDN

Aviad P.
May not work the way you'd expect. The single click notification is fired even for double clicks...
Kent Boogaart
have you tried that example? it just doesn't work in that if you try to catch all three, no matter how many times you click it will register as a single-click, since a double-click is two single-clicks etc.
Edward Tanguay
A: 

You need to fire the event after the click sequence is over... when is that? I suggest using a timer. The MouseDown event would reset it and increase the click count. When timer interval elapses it makes the call to evaluate the click count.

    private System.Timers.Timer ClickTimer;
    private int ClickCounter;

    public MyView()
    {
        ClickTimer = new Timer(300);
        ClickTimer.Elapsed += new ElapsedEventHandler(EvaluateClicks);
        InitializeComponent();
    }

    private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
    {
        ClickTimer.Stop();
        ClickCounter++;
        ClickTimer.Start();
    }

    private void EvaluateClicks(object source, ElapsedEventArgs e)
    {
        ClickTimer.Stop();
        // Evaluate ClickCounter here
        ClickCounter = 0;
    }

Cheers!

Natxo