iamsophia
iamsophia

Reputation: 796

How can I make a TapGestureRecognizer called a method in my class using a command instead of an event?

I have this code:

public ScrollHeadingView2()
{
   outerGrid = new Grid() { BackgroundColor = Color.Red, RowSpacing = 0, ColumnSpacing = 0 };
   outerGrid.AddChild(new BoxView() 
   { 
      HeightRequest = 100, 
      WidthRequest = 100, 
      BackgroundColor = Color.Pink 
   }, 0, 0);
   var tap1 = new TapGestureRecognizer() 
   { 
      NumberOfTapsRequired = 1 
   }
   tap1.Tapped += async (s, o) => { await BackArrowTapped(); };

   grid1.GestureRecognizers.Add(tap1);
}

private async Task BackArrowTapped()
{
    await Shell.Current.Navigation.PopAsync(false);
}

I am trying this method using an event but it seems to be firing twice. Can someone tell me how I could replace the event with a command to call BackArrowTapped()?

Upvotes: 0

Views: 140

Answers (1)

Jason
Jason

Reputation: 89102

there is an example that specifically covers this scenario in the docs

tap1.SetBinding(TapGestureRecognizer.CommandProperty, "TapCommand");

then

ICommand tapCommand;

public TapViewModel () {
    // configure the TapCommand with a method
    tapCommand = new Command (OnTapped);
}
public ICommand TapCommand {
    get { return tapCommand; }
}
void OnTapped (object s)  {
    taps++;
    Debug.WriteLine ("parameter: " + s);
}

Upvotes: 1

Related Questions