pnizi
pnizi

Reputation: 65

WPF: Figuring out whether a MouseBinding is a single click or double click

Im using Mousebindings in my view to listen to user clicks like this:

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

I only need one of the mouse gestures at a time. So if I double click on my application I want to ignore the single left click mousebinding. Possibly like waiting 1-2sec after the initial mouseclick then decided which should be called. Is there a simple way of doing this?

Upvotes: 3

Views: 1918

Answers (1)

Breeze
Breeze

Reputation: 2058

I got it working the following way (I used a Button to test it, you'll have to adapt it).

  1. Use Event Handlers

    <Button MouseDoubleClick="Button_MouseDoubleClick" Click="Button_Click"></Button>
    
  2. store the DataContext in a static variable

    private static object context;
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel();
        context = DataContext;
    }
    
  3. Adapt this code (I mainly got it from 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");
    }
    

Upvotes: 1

Related Questions