2009-06-09 384 views
14

我必須同時處理單擊和雙擊WPF應用程序中按鈕的不同反應。 不幸的是,在雙擊時,WPF會觸發兩個單擊事件和一個雙擊事件,所以很難處理這種情況。WPF:Button單擊+雙擊問題

它試圖用計時器解決它,但沒有成功......我希望你能幫助我。

讓我們來看看代碼:

private void delayedBtnClick(object statInfo) 
{ 
    if (doubleClickTimer != null) 
     doubleClickTimer.Dispose(); 
    doubleClickTimer = null; 

    this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new VoidDelegate(delegate() 
    { 
     // ... DO THE SINGLE CLICK ACTION 
    })); 
} 

private void btn_Click(object sender, RoutedEventArgs e) 
{ 
    if (doubleClickTimer == null) 
     doubleClickTimer = new Timer(delayedBtnClick, null, System.Windows.Forms.SystemInformation.DoubleClickTime, Timeout.Infinite); 
     } 
    } 
} 

private void btnNext_MouseDoubleClick(object sender, MouseButtonEventArgs e) 
{ 
    if (doubleClickTimer != null) 
     doubleClickTimer.Change(Timeout.Infinite, Timeout.Infinite); // disable it - I've tried it with and without this line 
     doubleClickTimer.Dispose(); 
    doubleClickTimer = null; 

    //.... DO THE DOUBLE CLICK ACTION 
} 

的問題是,「只需點擊一下行動」上雙擊的「雙擊動作」後調用。這是奇怪的是,我設置了doubleClickTimer爲null上雙擊,但在delayedBtnClick這是真的:O型

我已經嘗試過使用更長的時間,一個布爾標誌和鎖...

你有什麼想法?

最好!

回答

16

如果設置了RoutedEvente.Handledtrue處理MouseDoubleClick事件發生後,那麼它不會調用Click事件第二次MouseDoubleClick後。

有一個recent post觸及具有不同的行爲SingleClickDoubleClick這可能是有用的。

但是,如果你確定要單獨行爲,並希望/需要阻止第一Click以及第二Click,您可以使用DispatcherTimer喜歡你。

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"); 
} 
+0

非常感謝! e.Handled = true是訣竅! 再次感謝您的快速反應:) – Hunsoul 2009-06-10 08:14:48

+1

如果您使用該構造函數的DispatcherTimer計時器立即啓動,這將導致一個虛假的單擊事件。另外背景和當前是默認值,所以混淆了一些東西(以爲可能會有一些巫術出現在那裏!)。非常有用 - 乾杯! – 2013-01-16 16:55:09

6

你可以試試這個:

Button.MouseLeftButtonDown += Button_MouseLeftButtonDown; 

private void Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) 
{ 
    e.Handled = true; 

    if (e.ClickCount > 1) 
    { 
     // Do double-click code 
    } 

    else 
    { 
     // Do single-click code 
    } 
} 

如果neccessary,你可能需要點擊鼠標,等到鼠標向上執行的操作。