无法添加2个TapGestureRecognizer?

时间:2017-12-02 11:43:08

标签: xamarin xamarin.forms

我的自定义控件上有2个TapGestureRecognizers:

1) 第一个是内部/仅存在于自定义控件中。

2) 第二个附加在自定义控件实例化的页面上。

我正在使用第一个TapGestureRecognizer在内部/自定义控件内的Tap上触发动画,第二个TapGestureRecognizer用于跟踪页面上自定义控件的点击,以便我可以对点击做出反应。

在“页面外”/页面上进行动画感觉不对,因为此控件的每个实例都应该设置动画,这就是我在自定义控件中附加TapGestureRecognizer的原因。

然而,当我这样做时,只有“内部”TapGestureRecognizer工作,外面的那个没有。

这是正常行为吗?

public class clsGridCell : ContentView
{

     var _Grid1ContainerForImageAndLabel = new Grid()
     {
     }

     var nTapRec = new TapGestureRecognizer();
     nTapRec.Tapped += OnItemSelected;
     _Grid1ContainerForImageAndLabel.GestureRecognizers.Add(nTapRec);

     this.Content = _Grid1ContainerForImageAndLabel;

     }

     private async void OnItemSelected(object sender, EventArgs e)
     {
         await Task.WhenAny<bool>
         (
            _image1.ScaleTo(0.9, 50, Easing.Linear)
         );

        //run some background color animation, too
    }

和“在外面”/在页面上:

public class MainPage : ContentPage
{
     var nGridCell = new clsGridCell                            
     {
         ImageSource = nImgSrc,
         BackgroundColor = Color.Blue;
     };

     _BigGrid.Children.Add(nGridCell);

     var nTapRec = new TapGestureRecognizer();
     nTapRec.Tapped += OnItemSelected;
     nGridCell.GestureRecognizers.Add(nTapRec);

    private async void OnItemSelected(object sender, EventArgs e)
    {
         //Not fired! When I remove the "internal" TapGestureRecognizer, it does work

1 个答案:

答案 0 :(得分:1)

只需将内部TapGestureRecognizer创建为该类的公共/内部属性,而不是创建新的手势&#34;在&#34;之外,向该类添加新的Tapped操作&#34; TapGestureRecognizer。像这样:

public class clsGridCell : ContentView     
{ 
    public TapGestureRecognizer TapGesture { get; set; }

    Action<clsGridCell> tap;
    public Action<clsGridCell> Tap
    {
        get => tap;
        set
        {
            tap = value;
            TapGesture.Tapped += (sender, e) => { value(this); };
        }
    }

    public clsGridCell()
    {
        var _Grid1ContainerForImageAndLabel = new Grid() { };

        TapGesture = new TapGestureRecognizer(); 
        TapGesture.Tapped += OnItemSelected; 
        _Grid1ContainerForImageAndLabel.GestureRecognizers.Add(TapGesture); 

        this.Content = _Grid1ContainerForImageAndLabel; 
    } 

    private async void OnItemSelected(object sender, EventArgs e) 
    { 
        await Task.WhenAny<bool> ( _image1.ScaleTo(0.9, 50, Easing.Linear) ); //run some background color animation, too
    }
}

外部使用myGrid.Tap = Method;