0

我有一个包含矩形的二维数组。它们存储在动态的 UniformGrid 中。如何找出数组中的哪个矩形是 MouseDown?

我试过了,但我一直得到 [0,0]:

if (e.OriginalSource is Shape s)
{
    cellRow = (int)s.GetValue(Grid.RowProperty);
    cellColumn = (int)s.GetValue(Grid.ColumnProperty);
    rectangle[cellRow,cellColumn].Fill = new SolidColorBrush(Colors.Black);
}

这就是我生成矩形的方式:

rectangle = new Rectangle[rowcol, rowcol];
for (int x = 0; x < rowcol; x++)
{
    for (int y = 0; y < rowcol; y++)
    {
        rectangle[y, x] = new Rectangle { Stroke = Brushes.Black, StrokeThickness = 0.5, Fill = Brushes.White };
        GameUniformGrid.Children.Add(rectangle[y, x]);
    }
}

xaml 中的 MouseDown 事件: <UniformGrid x:Name="GameUniformGrid" HorizontalAlignment="Left" Height="272" VerticalAlignment="Top" Width="272" Grid.Row="0" Grid.Column="0" Rectangle.MouseDown="ToggleGrid"/>

4

1 回答 1

0

我认为问题在于初始化一个矩形,当您使用多维数组时,您有一些行和列,而您正在做的只是在行和列中都使用行。如果 rowcol =0 怎么办?由于这种情况,循环不会运行。

x < 行列 (0<0);

你应该

rectangle = new Rectangle[row, col];
    for (int x = 0; x < row; x++)
    {
        for (int y = 0; y < col; y++)
        {
            rectangle[y, x] = new Rectangle { Stroke = Brushes.Black, StrokeThickness = 0.5, Fill = Brushes.White };
            GameUniformGrid.Children.Add(rectangle[y, x]);
        }
    }

(例如)

其中行 = 2,列 = 2

于 2018-08-21T14:10:35.743 回答