How can I added a “.Tapped += async (s, e) => {. ….” directly to a new TapGestureRecognizer();?

Issue

Here is the code that I have:

        TapGestureRecognizer tap1  new TapGestureRecognizer()
        .Bind(TapGestureRecognizer.CommandProperty, nameof(TapCommand), source: this)
        .Bind(TapGestureRecognizer.CommandParameterProperty, nameof(TapCommandParam), source: this);
        GestureRecognizers.Add(tap1);

        TapGestureRecognizer tap2  new TapGestureRecognizer();
        tap2.Tapped + async (s, e) > {
            this.SetDynamicResource(BackgroundColorProperty, "GridTappedColor");
            await Task.Delay(500);
            this.BackgroundColor  Color.Default;
        };
        GestureRecognizers.Add(tap2);

What I would like to know is if there is a way I can added the following code:

        .Tapped + async (s, e) > {. ....

Directly to this:

        tap2  new TapGestureRecognizer()

Something like this:

        TapGestureRecognizer tap2  new TapGestureRecognizer().Tapped()

Solution

The basic idea would be to have an extension that lets you do something with the item and return the very same item.

public static class TapGestureRecognizerExtensions {
    public static TapGestureRecognizer BindAction( 
         this TapGestureRecognizer recognizer, 
         Action<TapGestureRecognizer> action ) {
             action(recognizer);
             return recognizer;
    }
}

...

TapGestureRecognizer tap2  
    new TapGestureRecognizer().BindAction( 
      t >
        t.Tapped + async (s, e) > {
            this.SetDynamicResource(BackgroundColorProperty, "GridTappedColor");
            await Task.Delay(500);
            this.BackgroundColor  Color.Default;
       };
    );

Answered By – Wiktor Zychla

Leave a Comment