繁体   English   中英

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

[英]How to change the colour of a rectangle present in a XAML grid cell if i know the grid cell position using C#

我有一个动态生成的 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
    }

保持这样的字典可能比尝试通过网格的子节点查找 Rectangle 更容易、更便宜

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM