我需要编写一个函数,在运行程序期间根据某些条件设置 TableLayoutPanel
单元格中的颜色。
TableLayoutPanel
被 16x16 分割。程序开始时有一些条件。如果该单元格的条件为真,则该单元格必须涂成蓝色。例如:
private void start_Click(object sender, EventArgs e)
{
foreach (string str in some_list)
{
if (some condition)
{
set_color_in_cell at row[i] colum[j] //(what shoud i use here?)
}
}
}
我找到了这样的例子:
private void tableLayoutPanel_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
{
if (e.Row == 0 && e.Column == 1)
{
e.Graphics.FillRectangle(new SolidBrush(Color.Black), e.CellBounds);
}
}
但我不明白如何使用它。如果有人知道这件事,请帮助我。
private void start_Click(object sender, EventArgs e)
{
string SyncAnswer = "";
foreach (string file_string in Data_from_file)
{
COM_Port.WriteLine(file_string);
while (SyncAnswer != "READY")
{
SyncAnswer = COM_Port.ReadLine();
if (SyncAnswer.Substring(0, 4) == "Fire")
{
//raise event
//paint for example a cell in Row=i Colum=j
}
else if (SyncAnswer.Substring(0, 4) == "Skip")
{
//raise event
}
}
}
}
最佳答案
选项 1 - 使用 CellPaint事件
这是一个一步一步的例子:
- 创建
Form
- 放一个
TableLayoutPanel
从你的工具箱Form
- 选择
tableLayoutPanel1
在设计界面上,然后按 F4 键查看属性。 - 从属性网格的工具栏中,您可以选择显示属性 或事件 。单击事件图标,然后从列表中双击
CellPaint
要创建的事件tableLayoutPanel1_CellPaint
代码中的事件处理程序。 - 您可以根据某些标准在此方法中为每个单元格绘制背景。该事件将引发绘制每个单元格背景和
e.Row
是行索引,e.Column
是列索引,e.CellBounds
是绘画细胞的边界。
例如在下面的示例中,我们绘制黑色背景 if ((e.Column + e.Row) % 2 == 1)
否则,我们绘制白色背景:
private void tableLayoutPanel1_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
{
if ((e.Column + e.Row) % 2 == 1)
e.Graphics.FillRectangle(Brushes.Black, e.CellBounds);
else
e.Graphics.FillRectangle(Brushes.White, e.CellBounds);
}
动态改变颜色
从另一个程序点更改颜色,例如在 Click
中按钮事件,您应该将每个单元格的背景颜色存储在二维数组中,并使用该颜色为该单元格创建画笔:
定义bgColors
在你的表格中:
Color[,] bgColors = new Color[2, 2] {
{ SystemColors.Control, SystemColors.Control },
{ SystemColors.Control, SystemColors.Control }
};
这样绘制单元格背景:
private void tableLayoutPanel1_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
{
using (var b = new SolidBrush(bgColors[e.Column, e.Row]))
{
e.Graphics.FillRectangle(b , e.CellBounds);
}
}
要更改 BackColor
的 Cell
你可以:
private void Button1_Click(object sender, EventArgs e)
{
//column: 0 ,row: 1
bgColors[0, 1] = Color.Red;
tableLayoutPanel1.Refresh();
}
选项 2 - 在单元格中托管面板
作为另一个简单的选项,您可以输入 Panel
在每个单元格中,设置 Dock
Panel
的属性(property)至 Fill
并设置它的 Margin
属性(property)0,0
, 那么每次你想改变位置 (column, row)
的面板颜色时你可以使用这段代码:
this.tableLayoutPanel1.GetControlFromPosition(column, row).BackColor = Color.Red;
关于c# - 如何在 TableLayoutPanel 中动态设置单元格颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34064499/