如果我知道使用 C# 的网格单元格位置,如何更改 XAML 网格单元格中存在的矩形的颜色



我有一个动态生成的 XAML 网格,并在每个单元格中插入了矩形对象,以便以后可以根据需要更改它们的颜色。我无法弄清楚的是,如果我只知道要访问的单元格行号和列号以及网格名称,当我想要访问时,如何访问 C# 中的矩形对象。我尝试在现有对象上插入新的 Rectangle 对象,但在我的代码中,这给了我堆栈溢出异常。任何帮助将不胜感激。

XAML 代码-

<Grid ShowGridLines="True" x:Name="AnswerGrid" Width="500" Height="400" Margin="2"
    Background="Transparent" PreviewMouseLeftButtonDown="OnPreviewMouseLeftButtonDown">
</Grid>

网格中的 C# 矩形对象

Rectangle rect = new Rectangle();
Grid.SetRow(rect, i);
Grid.SetColumn(rect, j);
rect.Fill = new SolidColorBrush(System.Windows.Media.Colors.AliceBlue);
AnswerGrid.Children.Add(rect);

我正在每个单元格中使用行,列和矩形对象动态填充此网格。我想更改特定单元格中矩形的背景颜色。

您需要以某种方式跟踪矩形,方法是从现有网格访问它,或者使用字典查找矩形,如下所示

    Dictionary<int, Rectangle> _rectDict = new Dictionary<int, Rectangle>();
    int _maxCol = 10;
    private void AddRectangle(int i, int j)
    {
        Rectangle rect = new Rectangle();
        Grid.SetRow(rect, i);
        Grid.SetColumn(rect, j);
        rect.Fill = new SolidColorBrush(System.Windows.Media.Colors.AliceBlue);
        AnswerGrid.Children.Add(rect);
        _rectDict[i * _maxCol + j] = rect;
    }
    private void ChangeColour(int i, int j, Color color)
    {
        Rectangle rect = _rectDict[i * _maxCol + j];
        // Change colour of rect
    }

保留这样的字典可能比尝试通过网格的子项查找矩形更容易、更便宜。

最新更新