Click Event should not trigger when hold event per

2019-03-04 03:57发布

问题:

i have button in my windows phone silverlight 8.1 app i created two event one click event and second hold event, i want when user hold such button then click event should not fire, but currently when i hold button and then leave that button click button also fires, so how to handle that.

 private void ExtraButton_Click(object sender, RoutedEventArgs e)
 {

 }

 private void ExtraButton_Hold(object sender, GestureEventArgs e)
 {

 }

so how to cancel click event when hold event performed.

回答1:

I suggest you can replace the Button Click event with Button Tap event, because when you hold this button, the Button Hold event will be triggered firstly.

        private void button1_Hold(object sender, System.Windows.Input.GestureEventArgs e)
    {
        e.Handled = true;  
        MessageBox.Show("button have been holded");

    }

    private void button1_Tap(object sender, System.Windows.Input.GestureEventArgs e)
    {
        MessageBox.Show("button have been tapped");
        //your code goes here
    }

After you set Handled property as true, then the Button Click event will not handle your gesture.



回答2:

You can achieve your requirement by unwire the button click event while holding and again wire the click event in PointerExited event. Refer the below code snippet.

Button btn = new Button();

btn.Holding += Btn_Holding;

btn.Click += Btn_Click;

btn.PointerExited += Btn_PointerExited;


        private void Btn_PointerExited(object sender, PointerRoutedEventArgs e)
        {
            btn.Click += Btn_Click;
        }

        private void Btn_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Btn_Holding(object sender, HoldingRoutedEventArgs e)
        {
            btn.Click -= Btn_Click;
        }

In PointerExited event, you can hook the click event only if it is not already hooked using some conditions. It will improve the performance.



回答3:

Use Button_Hold and Button_Tap events to achieve your requirement.