WPF:计算鼠标绑定是单击还是双击

本文关键字:单击 双击 绑定 计算 鼠标 WPF | 更新日期: 2023-09-27 18:00:49

我在视图中使用Mousebindings来监听用户点击,如下所示:

<Path.InputBindings>
            <MouseBinding Gesture="LeftDoubleClick" Command="{Binding DoubleLeftClickProj}" />
            <MouseBinding Gesture="LeftClick" Command="{Binding SingleLeftClick}"/>
</Path.InputBindings>

我一次只需要一个鼠标手势。因此,如果我双击我的应用程序,我想忽略单次左键鼠标绑定。可能就像在最初的鼠标点击后等待1-2秒,然后决定应该调用哪个。有简单的方法吗?

WPF:计算鼠标绑定是单击还是双击

我用下面的方式让它工作(我用了一个按钮来测试它,你必须调整它(。

  1. 使用事件处理程序

    <Button MouseDoubleClick="Button_MouseDoubleClick" Click="Button_Click"></Button>
    
  2. 将DataContext存储在静态变量中

    private static object context;
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel();
        context = DataContext;
    }
    
  3. 改编这个代码(我主要是从https://stackoverflow.com/a/971676/4792869)

    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();
        ((ICommand)DataContext).Execute("DoubleLeftClickProj");
        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
        ((ICommand)context).Execute("SingleLeftClick");
    }