【问题标题】:How to change the colour of a rectangle present in a XAML grid cell if i know the grid cell position using C#如果我知道使用 C# 的网格单元格位置,如何更改 XAML 网格单元格中存在的矩形的颜色
【发布时间】:2017-01-30 08:37:34
【问题描述】:

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

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

【问题讨论】:

  • 您需要粘贴您正在使用的 xaml/C# 代码,我们才能为您提供帮助..
  • 请再检查一遍
  • “我尝试在现有对象上插入新的 Rectangle 对象,但在我的代码中,这给了我一个堆栈溢出异常” - 您还应该向我们展示您尝试过的导致错误的代码。不过,我已经给出了答案。

标签: c# xaml visual-studio-2015


【解决方案1】:

您需要以某种方式跟踪矩形,或者通过从现有网格访问它,或者使用字典来找到这样的矩形

    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 更容易且更便宜

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    • 2013-04-17
    • 2011-10-05
    相关资源
    最近更新 更多