Page 1 of 1

Double-click event?

Posted: Sun Jan 15, 2017 2:53 am
by tomny
Dear JS-Support,

I want a controls (Image, TextBlock ...) to achieve a double-click event, how to achieve it?

Thank you.
Regards,
Tomny

Re: Double-click event?

Posted: Wed Jan 18, 2017 7:32 am
by JS-Support @Userware
Dear Tomny,

Sure!

Here is how you can add a DoubleClick event to an existing control.

Let's create a TextBlock2 class that inherits from TextBlock:

Code: Select all

public class TextBlock2 : TextBlock
{
    private DateTime _lastPointerPressed = DateTime.Now;
    public event PointerEventHandler DoubleClick;

    public TextBlock2()
    {
        this.PointerPressed += MainPage_PointerPressed;
    }

    void MainPage_PointerPressed(object sender, PointerRoutedEventArgs e)
    {
        DateTime now = DateTime.Now;
        if ((now - _lastPointerPressed).TotalMilliseconds <= 300)
        {
            if (DoubleClick != null)
            {
                DoubleClick(this, e);
            }
            e.Handled = true;
        }
        _lastPointerPressed = now;
    }
}


To test it, just declare it somewhere in your xaml code:

Code: Select all

<local:TextBlock2 Text="Double-click me to test" DoubleClick="TextBlock2_DoubleClick"/>


and use the following code-behind:

Code: Select all

void TextBlock2_DoubleClick(object sender, PointerRoutedEventArgs e)
{
    MessageBox.Show("Double-click works!");
}


Regards,
JS-Support