Reputation:
I have a 2D array that contains rectangles. They are stored in a dynamic UniformGrid. How do I find out which rectangle in the array was MouseDown?
I tried this but I keep getting [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);
}
And this is how I generated the rectangles:
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]);
}
}
The MouseDown event in xaml:
<UniformGrid x:Name="GameUniformGrid" HorizontalAlignment="Left" Height="272" VerticalAlignment="Top" Width="272" Grid.Row="0" Grid.Column="0" Rectangle.MouseDown="ToggleGrid"/>
Upvotes: 0
Views: 129
Reputation: 5291
I think the problem is with initializing a rectangle, When you work with multidimentional array you have some rows and column and what you are doing is using row only in both row,column. What if rowcol =0 ? the loop will not run because this condition.
x < rowcol (0<0);
You should
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]);
}
}
(For example)
where row = 2 ,col =2
Upvotes: 0