为了绘制单元矩阵,我使用了由以下代码定义的Stackpanel:
int columns = Convert.ToInt32(columnasText.Text);
int rows = Convert.ToInt32(filasText.Text);
SolidColorBrush selected1 = new SolidColorBrush(Colors.Aquamarine);
SolidColorBrush released = new SolidColorBrush(Colors.White);
for (int i = 0; i < rows; i++)
{
StackPanel stkPanel = new StackPanel();
stkPanel.Orientation = Orientation.Horizontal;
for (int j = 0; j < columns; j++)
{
Label lbl = new Label();
lbl.Height = rejilla.Height / rows;
lbl.Width = rejilla.Width / columns;
lbl.Tag = new Point(i, j);
lbl.BorderBrush = new SolidColorBrush(Colors.Black);
lbl.BorderThickness = new Thickness(1);
lbl.Background = released;
stkPanel.Children.Add(lbl);
}
rejilla.Children.Add(stkPanel);
一旦定义了,我需要根据每个单元格的值来更改每个单元格的颜色,而我无法做到这一点。
答案 0 :(得分:1)
我使用了您的变量rejilla(我假设它是StackPanel或Grid)。无论哪种方式,它都可以工作。
密钥正在使用 .Children.OfType()
//Get your cell location
int rowIndex = 2;
int columnIndex = 8;
//Get your desired new color
SolidColorBrush selected1 = new SolidColorBrush(Colors.Aquamarine);
//Get list of your row panels
var stackPanels = rejilla.Children.OfType<StackPanel>().ToList();
//Check if desired row panel exist
if (rowIndex < stackPanels.Count && rowIndex >= 0)
{
//Get list of your labels in the desired row panel
var labels = stackPanels[rowIndex].Children.OfType<Label>().ToList();
//Check if desired cell exist or not then change background
if (columnIndex < labels.Count && columnIndex >= 0)
labels[columnIndex].Background = selected1;
}
不推荐,如果将所有标签放置在一个堆栈面板中而不是将它们放置在多个堆栈面板中(每行一个堆栈面板),此方法将很有用。
//Get your cell location
int rowIndex = 2;
int columnIndex = 8;
//Get your desired new color
SolidColorBrush selected1 = new SolidColorBrush(Colors.Aquamarine);
//Get list of your row panels
var stackPanels = rejilla.Children.OfType<StackPanel>().ToList();
//Check if desired row panel exist
if (rowIndex < stackPanels.Count && rowIndex >= 0)
{
//Get list of your labels in the desired row panel
var label = stackPanels[rowIndex].Children.OfType<Label>()
.Where(Item => (int)(Item.Tag as Nullable<Point>).GetValueOrDefault().X == rowIndex
&& (int)(Item.Tag as Nullable<Point>).GetValueOrDefault().Y == columnIndex).FirstOrDefault();
if(label != null)
label.Background = selected1;
}
private void SetCellColor(StackPanel stackPanel, SolidColorBrush color, int rowIndex, int columnIndex)
{
//Get list of your row panels
var stackPanels = stackPanel.Children.OfType<StackPanel>().ToList();
//Check if desired row panel exist
if (rowIndex < stackPanels.Count && rowIndex >= 0)
{
//Get list of your labels in the desired row panel
var labels = stackPanels[rowIndex].Children.OfType<Label>().ToList();
//Check if desired cell exist or not then change background
if (columnIndex < labels.Count && columnIndex >= 0)
labels[columnIndex].Background = color;
}
}
SetCellColor(rejilla, new SolidColorBrush(Colors.Aquamarine), rowIndex, columnIndex);
祝你好运!