uwp 通过单击单元格获取网格中的位置

uwp get position in grid by clicking a cell

我有一个包含所有空单元格的网格,现在我想在用户单击屏幕时获取坐标。我如何知道单击了哪个单元格和单元格位置? 请帮助我

        gameboard.HorizontalAlignment = HorizontalAlignment.Stretch;
        gameboard.VerticalAlignment = VerticalAlignment.Stretch;
        gameboard.Width = Window.Current.Bounds.Width;
        gameboard.Height = Window.Current.Bounds.Width;

        for (int j = 0; j < 7; j++)
        {
            var cd = new ColumnDefinition();
            cd.Width = new GridLength(1, GridUnitType.Star);
            var rd = new RowDefinition();
            rd.Height = new GridLength(1, GridUnitType.Star);
            gameboard.ColumnDefinitions.Add(cd);
            gameboard.RowDefinitions.Add(rd);
        }

        for (int j = 0; j < 7; j++)
        {
            for (int k = 0; k < 7; k++)
            {
                Border border = new Border();
                border.BorderThickness = new Thickness(1);
                border.BorderBrush = new SolidColorBrush(Colors.Gray);
                border.HorizontalAlignment = HorizontalAlignment.Stretch;
                border.VerticalAlignment = VerticalAlignment.Stretch;
                Grid.SetColumn(border, j);
                Grid.SetRow(border, k);
                gameboard.Children.Add(border);
            }
        }
        canvas2.Children.Add(gameboard);

首先,将 Background 设置为您的 Border 以处理 Tap 事件:

border.Background = new SolidColorBrush(Colors.Transparent);
border.Tapped += Border_Tapped;

要获取 Border 元素的位置,您可以使用两种方法:

  • 检索您的 Grid
  • ColumnRow 索引
  • 检索相对于UIElement的点位置(例如:Window.Current.Content

    private void Border_Tapped(object sender, TappedRoutedEventArgs e)
    {
        // First way:
        var border = (Border)sender;
        var column = Grid.GetColumn(border);
        var row = Grid.GetRow(border);
    
        // Second way
        var point = e.GetPosition(Window.Current.Content);
    }