WPF:确定MouseBinding是单击还是双击

时间:2015-07-02 18:05:52

标签: c# wpf mouseevent

我在视图中使用鼠标绑定来收听用户点击,如下所示:

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

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

1 个答案:

答案 0 :(得分:1)

我按照以下方式使用它(我使用了一个Button来测试它,你必须对它进行调整)。

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