WPF: Button single click + double click issue

后端 未结 2 1423
傲寒
傲寒 2020-11-29 12:13

I have to handle both the single click and the double click of a button in a WPF application with different reaction. Unfortunately, on a doubleclick, WPF fires two click ev

2条回答
  •  情书的邮戳
    2020-11-29 12:44

    If you set the RoutedEvent's e.Handled to true after handling the MouseDoubleClick event then it will not call the Click Event the second time after the MouseDoubleClick.

    There's a recent post which touches on having different behaviors for SingleClick and DoubleClick which may be useful.

    However, if you are sure you want separate behaviors and want/need to block the first Click as well as the second Click, you can use the DispatcherTimer like you were.

    private static DispatcherTimer myClickWaitTimer = 
        new DispatcherTimer(
            new TimeSpan(0, 0, 0, 1), 
            DispatcherPriority.Background, 
            mouseWaitTimer_Tick, 
            Dispatcher.CurrentDispatcher);
    
    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");
    }
    

提交回复
热议问题