我正在尝试以编程方式更改TableLayoutPanel
内的表格单元格的背景颜色。单元格可以是null
,也可以在运行时由用户控件获取(始终更改)。
我这样做:
TableName.GetControlFromPosition(column, row).BackColor = Color.CornflowerBlue;
当然,只有在该单元格中存在某些内容时,这才有效。如何在运行时更改空单元格的属性?
答案 0 :(得分:1)
当单元格为null时,您无法设置它的BackColor属性。设置颜色时,应检查它是否为空。您可以在单元格中设置控件的颜色,而不是单元格的BackColor。 https://jsfiddle.net/webarthur/3ep33h5s/1/
答案 1 :(得分:1)
请注意,TableLayoutPanelCell
确实没有这样的东西。 “细胞”严格虚拟。
您可以使用CellPaint
事件将任何BackColor
绘制到任何“单元格”上,空白与否:
private void tableLayoutPanel1_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
{
if (e.Row == e.Column)
using (SolidBrush brush = new SolidBrush(Color.AliceBlue))
e.Graphics.FillRectangle(brush, e.CellBounds);
else
using (SolidBrush brush = new SolidBrush(Color.FromArgb(123, 234, 0)))
e.Graphics.FillRectangle(brush, e.CellBounds);
}
当然,颜色和条件取决于你......
更新:请再次注意,您无法为某个“单元格”着色,因为 没有TableLayoutPanelCells
!没有这样的类,既不是控制也不是对象。它只是不存在! TLP 不由“单元格”组成。它仅由行和列组成。
因此要为'单元'着色,您需要在CellPaint
事件中编码一个合适的条件,这是最接近使用名称'cell'的.NET。
您可以根据需要使用简单公式或显式枚举来创建所需的颜色布局。
以下是两个更详细的例子:
对于简单的棋盘布局,请使用以下条件:
if ((e.Row + e.Column) % 2 == 0)
对于自由格式布局,收集Dictionary<Point>, Color
中的所有颜色值;
Dictionary<Point, Color> cellcolors = new Dictionary<Point, Color>();
cellcolors.Add(new Point(0, 1), Color.CadetBlue);
cellcolors.Add(new Point(2, 4), Color.Blue);
..
..
..
并写:
private void tableLayoutPanel1_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
{
if (cellcolors.Keys.Contains(new Point(e.Column, e.Row )))
using (SolidBrush brush = new SolidBrush(cellcolors[new Point(e.Column, e.Row )]))
e.Graphics.FillRectangle(brush, e.CellBounds);
else
using (SolidBrush brush = new SolidBrush(defaultColor))
e.Graphics.FillRectangle(brush, e.CellBounds);
}