2017-01-30 29 views
1

我有一個XAML網格,我已動態生成並在每個單元格中插入矩形對象,以便我可以更改它們之後我想要的顏色。 我無法弄清楚的是如何訪問C#中的矩形對象,當我想如果我只知道要訪問的單元格行和列號以及網格名稱。 我已經嘗試插入新的Rectangle對象而不是現有的,但在我的代碼,給我一個堆棧溢出異常。 任何幫助將不勝感激。如何更改XAML網格單元格中存在的矩形的顏色,如果我知道使用C#的網格單元格位置#

XAML代碼 -

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

下在網格狀

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); 

我動態填充該網格具有行,列和矩形對象在每個cell.I#矩形對象要更改的背景矩形在特定單元格中的顏色。

+1

您需要先粘貼您使用的xaml/C#代碼,然後才能幫助您。 – Ben

+0

請再檢查一次 –

+0

「我嘗試在現有插件上插入新的Rectangle對象但在我的代碼中,給我一個堆棧溢出異常「 - 你也應該顯示我們已經嘗試過的代碼導致錯誤。儘管如此,我已經給出了答案。 – Ben

回答

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 
    } 

保持字典這樣可能會更容易矩形並且比試圖通過網格的孩子找到矩形要便宜

相關問題