如何将“ .Tapped + =异步s,e=> {....”直接添加到新的TapGestureRecognizer;中?

问题描述

这是我拥有的代码

        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);

我想知道的是是否可以添加以下代码

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

直接为此:

        tap2 = new TapGestureRecognizer()

类似这样的东西:

        TapGestureRecognizer tap2 = new TapGestureRecognizer().Tapped()

解决方法

基本思想是拥有一个扩展名,该扩展名使您可以对商品进行处理并返回相同的商品。

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;
       };
    );