简体   繁体   中英

How do we separate click and double click on listview in WPF application?

I have a WPF application. There is a listview in which a every time I click or double click, the click event fires up. Even if I keep the Click Event, it automatically fires up when I Double click it. And if I bind the action in DoubleClick, it won't work in single click.

How can I handle both separately?

Add a handler to your control:

<SomeControl  MouseDown="MyMouseHandler">
...
</SomeControl>

The handler code:

private void MyMouseHandler(object sender, MouseButtonEventArgs e)
{
    if (e.ClickCount == 2)
    {
        //Handle here
    }
}

Please try following code snippet:

     if (e.ChangedButton == MouseButton.Left && e.ClickCount == 2) {
        // your logic here
    }

For details try this link on MSDN

The second click of a double-click is by definition always preceded by a single click.

If you don't want to handle it you could use a timer to wait for like 200 ms to see if there is another click before you actually handle the event:

public partial class MainWindow : Window
{
    System.Windows.Threading.DispatcherTimer _timer = new System.Windows.Threading.DispatcherTimer();
    public MainWindow()
    {
        InitializeComponent();
        _timer.Interval = TimeSpan.FromSeconds(0.2); //wait for the other click for 200ms
        _timer.Tick += _timer_Tick;
    }

    private void lv_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if(e.ClickCount == 2)
        {
            _timer.Stop();
            System.Diagnostics.Debug.WriteLine("double click"); //handle the double click event here...
        }
        else
        {
            _timer.Start();
        }
    }

    private void _timer_Tick(object sender, EventArgs e)
    {
        System.Diagnostics.Debug.WriteLine("click"); //handle the Click event here...
        _timer.Stop();
    }
}

<ListView PreviewMouseLeftButtonDown="lv_PreviewMouseLeftButtonDown" ... />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM