簡體   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