Search code examples
c#eventswpf-controlsmvvm-light

how to avoid click when I want double click?


I have an application in WPF and one button. In this buttun I want the click event that implement a code, but I want that when the do double click with the mouse, execute other code but not the code of the click event.

The problem is that the code of the click event is always executed and I don't know if there is a way to avoid the execution of the click event when I do doulbe click.

I am follow the MVVM pattern and I use MVVM light to convert the event into a command.

Thanks.


Solution

  • Set the RoutedEvent's e.Handled to True after handling the MouseDoubleClick event to block second click events of being fired.

    If you want to block first click event behavior, you can use a timer:

    private static DispatcherTimer myClickWaitTimer = 
        new DispatcherTimer(
            new TimeSpan(0, 0, 0, 0, 250), 
            DispatcherPriority.Normal, 
            mouseWaitTimer_Tick, 
            Dispatcher.CurrentDispatcher) { IsEnabled = false };
    
    private void Button_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        // Stop the timer from ticking.
        myClickWaitTimer.Stop();
    
        Trace.WriteLine("Double Click");
        e.Handled = true;
    }
    
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        myClickWaitTimer.Start();
    }
    
    private static void mouseWaitTimer_Tick(object sender, EventArgs e)
    {
        myClickWaitTimer.Stop();
    
        // Handle Single Click Actions
        Trace.WriteLine("Single Click");
    }