16

我必须同时处理具有不同反应的 WPF 应用程序中的按钮的单击和双击。不幸的是,在双击时,WPF 会触发两次单击事件和一次双击事件,因此很难处理这种情况。

它试图使用计时器解决它但没有成功......我希望你能帮助我。

让我们看看代码:

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在双击时将其设置为空,但delayedBtnClick它是真的:O

我已经尝试过使用更长的时间,一个布尔标志和锁......

你有什么想法?

最好的!

4

2 回答 2

16

如果您在处理事件后将RoutedEvent's设置e.Handled为,则它不会在.trueMouseDoubleClickClickMouseDoubleClick

最近有一篇文章谈到了不同的行为SingleClick并且DoubleClick可能有用。

但是,如果您确定想要单独的行为并且想要/需要阻止第一个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");
}
于 2009-06-09T18:17:39.867 回答
7

你可以试试这个:

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
    }
}

如有必要,您可能需要单击鼠标并等待鼠标向上执行操作。

于 2009-06-09T18:57:15.363 回答