C# 更改 TableLayoutPanel 中 table 单元格的背景颜色

C# Change background color of a table cell inTableLayoutPanel

我正在尝试以编程方式更改 TableLayoutPanel 中 table 单元格的背景颜色。单元格可以是 null 或在运行时由用户控件获取(始终更改)。

我是这样做的:

TableName.GetControlFromPosition(column, row).BackColor = Color.CornflowerBlue;

当然,这只有在该单元格中有东西时才有效。我还可以如何在运行时更改空单元格的属性?

当单元格为空时,不能设置它的BackColor 属性。设置颜色时,您应该检查它是否为空。您可以设置单元格中控件的颜色而不是单元格的背景色。 example

请注意,确实没有 TableLayoutPanelCell 这样的东西。 'cells' 是严格的 虚拟 .

您可以使用 CellPaint 事件将任何 BackColor 绘制到任何 'cell' 上,无论是否为空:

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

当然颜色和条件由你决定..

更新: 再次注意,您不能为某个 'cell' 着色,因为 没有 TableLayoutPanelCells !没有这样的 class,既没有控件也没有对象。它只是不存在! TLP 是由 而非 组成的 'cells'。它仅由行和列组成。

因此,要为 'cell' 着色,您需要在 CellPaint 事件中编写合适的条件,这是最接近使用名称 'cell'.[=21 的 .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);
}

你可以使用 TableLayoutPanel tlp = new TableLayoutPanel(); tlp.BackColor = Color.FromArgb(150,0,0,0);

这应该可以解决问题……