首页 > 解决方案 > Xamarin.Forms 在 Grid 子项中触发错误的点击事件

问题描述

我有几个对象GridTapGestureRecognizer但每当我点击任何生成的项目时,它总是会触发最新添加的事件。但是当我使用StackLayout而不是Grid触发事件时工作正常,但格式很乱。所以我想使用网格,但需要找出一些解决方法。AbsoluteLayout做同样的事情Grid

主要代码ContentPage

 private void Draw()
    {
        var hexagons = new List<Hexagon>();
        int x = 6, y = 40, id = 0;

        for (int i = 0; i < 7; i++)
        {
            for (int j = 0; j < 7; j++)
            {
                var hex = new Hexagon(id, x, y, 40);
                void Tapped()
                {
                    hex.SetHexaState(HexagonState.Tapped);
                }

                hex.Shape.GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(Tapped) });

                hexagons.Add(hex);
                y += 40;
                id++;
            }

            x += 34;
            y = i % 2 == 0 ? 20 : 40;
        }

        
        var grid = new Grid()
        {
        };

        hexagons.ForEach(rec => {
            grid.Children.Add(rec.Shape);
        });

        this.Content = grid;
    }

已在 Xamarin.Forms GitHub 上创建问题。

标签: xamarin.forms

解决方案


未定义列和行的 Grid 将在相同位置显示其子项,因此您的 Hexagons 可能会重叠并触发错误的 TapGestureRecognizer。如果您的 Hexagon 类正在执行其他一些定位逻辑,则由于您没有包含它,所以这并不明显。

对于自定义布局,请考虑使用AbsoluteLayout,您可以在其中设置子项的绝对/相对位置。


推荐阅读