How can I catch both single-click and double-click events on WPF FrameworkElement?

后端 未结 9 1523
鱼传尺愫
鱼传尺愫 2020-12-15 06:21

I can catch a single-click on a TextBlock like this:

private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
    MessageBo         


        
9条回答
  •  没有蜡笔的小新
    2020-12-15 06:33

    My issue was with single/double-clicking rows in a DataGrid in WPF. For some reason the ButtonDown events weren't firing, only the OnMouseLeftButtonUp event was. Anyway, I wanted to handle the single-click differently from the double-click. It looks me a little time (I'm sure the solution isn't perfect, but it appears to work) to distill the problem down until I got it down to the below. I created a Task which calls an Action and that Action's target can be updated by a second click. Hope this helps someone!

    private Action _clickAction;
    private int _clickCount;
    
    private void Grid_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        Debug.WriteLine("Button Click Occurred");
    
        _clickCount++;
    
        if (_clickCount == 1)
        {
            _clickAction = SingleClick;
        }
    
        if (_clickCount > 1)
        {
            _clickAction = DoubleClick;
        }
    
        if (_clickCount == 1)
        {
            Task.Delay(200)
                .ContinueWith(t => _clickAction(), TaskScheduler.FromCurrentSynchronizationContext())
                .ContinueWith(t => { _clickCount = 0; });
        }
    }
    
    private void DoubleGridClick()
    {
        Debug.WriteLine("Double Click");
    }
    
    private void SingleGridClick()
    {
        Debug.WriteLine("Single Click");
    }
    

提交回复
热议问题