以编程方式添加tapGesture的问题

时间:2020-03-09 15:45:12

标签: forms xamarin visual-studio-2019

有人可以帮我处理下面的代码示例吗?

for (int newCol = 0; newCol <= MaxCols; newCol++)
{
    for (int newRow = 0; newRow <= MaxRows / MaxCols; newRow++)
    {
        if (folderIndex >= DirectoryArrayList.Count) { break; }
        var folder = DirectoryArrayList[folderIndex];
        var label = new Label()
        {
            Text = folder.Name,
            FontSize = 12,
            VerticalTextAlignment = TextAlignment.Center,
            HorizontalTextAlignment = TextAlignment.Center
        };
        var GridBox = new BoxView() { BackgroundColor = Color.FromHex("#1ceaea") };
        var GridImage = new Image() { Source = "folder.png", StyleId= "Image"};
        var GridTap = new TapGestureRecognizer();
        GridTap.Tapped += async (sender, e) =>
        {
            string selectedFolder = MainFolder + folder.Name; // Will normally be a propertie stored in an array.
            if (Directory.Exists(selectedFolder))
            {
                //lstProperties.ItemsSource = selectedFolder; // Actual output purpose...
                await DisplayAlert("Folder", selectedFolder, "OK").ConfigureAwait(false); // Debug purposes...
                Console.WriteLine(selectedFolder); // Debug purposes...
            };
        };
        GridImage.GestureRecognizers.Add(GridTap);
        GridFolders.Children.Add(GridBox, newCol, newRow);
        GridFolders.Children.Add(GridImage, newCol, newRow);
        GridFolders.Children.Add(label, newCol, newRow);
        folderIndex += 1;
    }
}

我创建了一个GridTap var,当用户单击特定的GridImage时,它应该对点击手势做出反应,由于某种原因,它不起作用!我以为每个图像都没有唯一的名称/ ID可能是个问题,但是我找不到暗示它的方法。

通常的想法是拥有一个带有click事件的grid元素,并且将打开与之相似的文件夹,但这是迄今为止我发现的唯一与我想要做的事情相似的唯一方式< / p>

1 个答案:

答案 0 :(得分:1)

由于您要在同一行和同一列中添加3种不同的布局,因此位于最上方的元素将捕获您的GestureRecognizer,我建议您将所有内容包装到一个布局中,将GR传递给该布局,然后将其添加到您的GridFolders,如下所示:

var GridTap = new TapGestureRecognizer();
GridTap.Tapped += async (sender, e) =>
{
    ...
};
StackLayout LayoutToReceiveTheGesture = new StackLayout();
StackLayout.GestureRecognizers.Add(GridTap);
StackLayout.Children.Add(GridBox);
StackLayout.Children.Add(GridImage);
StackLayout.Children.Add(label);
GridFolders.Children.Add(GridBox, newCol, newRow);