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

后端 未结 9 1474
鱼传尺愫
鱼传尺愫 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:40

    My suggestion, implemented in a UserControl by simply using a Task:

    private int _clickCount = 0;
    protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
    {
        _clickCount = e.ClickCount;
    }
    
    protected override async void OnPreviewMouseUp(MouseButtonEventArgs e)
    {
        if (_clickCount > 1)
        {
            //apparently a second mouse down event has fired => this must be the second mouse up event
            //no need to start another task
            //the first mouse up event will be handled after the task below
            return; 
        }
    
        await Task.Delay(500);
    
        if (_clickCount == 1)
        {
            //single click
        }
        else
        {
            //double (or more) click
        }
    }
    

    The drawback of all these solutions is, of course, that there will be a delay before actually responding to the user's action.

提交回复
热议问题