【问题标题】:TableLayoutPanel NO Border Around First Column?TableLayoutPanel 第一列周围没有边框?
【发布时间】:2025-11-24 19:55:02
【问题描述】:

我有一个扩展 TableLayoutPanel 的类,定义/构造如下:

public class MyTableLayout : TableLayoutPanel
{
    public MyTableLayout()
    {
        this.ColumnCount = 5;
        this.RowCount = 1;
        this.CellBorderStyle = TableLayoutPanelCellBorderStyle.Outset;
    }
}

当我的表格被绘制时,它的所有 5 列都有边框(正如人们所期望的那样,因为代码可以设置上面的 CellBorderStyle)。

有什么方法可以防止在第一列周围绘制边框?

我知道你可以添加 CellPaint 回调:

this.CellPaint += tableLayoutPanel_CellPaint;

在这个回调中你可以做一些事情,比如改变特定列的边框颜色:

private void tableLayoutPanel_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
{
    if (e.Column == 0 && e.Row == 0)
    {
        e.Graphics.DrawRectangle(new Pen(Color.Red), e.CellBounds);
    }
}

但是你如何绘制“否”矩形呢?

我尝试将颜色设置为 Color.Empty 但这不起作用:

e.Graphics.DrawRectangle(new Pen(Color.Empty), e.CellBounds);

【问题讨论】:

    标签: c# winforms tablelayoutpanel


    【解决方案1】:

    单元格边框的绘制由 OnPaintBackground 覆盖中的 TableLayoutPanel 执行。

    要修改边框的绘制方式,您需要不设置边框(因此基类不会绘制任何内容),然后在您自己的 OnPaintBackground 覆盖中绘制所有其他边框。

    TableLayoutPanel 使用内部函数 ControlPaint.PaintTableCellBorder 来执行边框绘制。既然你不能使用它,你应该看看源代码(使用 Reflector 或 ILSpy),看看他们是如何做到的。

    【讨论】:

      【解决方案2】:

      换一种方式试试。只在你想要有边框的单元格周围绘制边框:

      private void tableLayoutPanel_CellPaint(object sender, 
                                              TableLayoutCellPaintEventArgs e) {
        if (e.Column > 0 && e.Row == 0) {
          e.Graphics.DrawRectangle(new Pen(Color.Red), e.CellBounds);
        }
      }
      

      显然,将您的边框设置回无,以便绘画可以接管工作:

      this.CellBorderStyle = TableLayoutPanelCellBorderStyle.None;
      

      【讨论】:

      • 不行,因为边框画是在OnPaintBackground完成的。
      • @JanTacci 我无法复制这些边缘被切掉的问题。不要使用e.CellBounds,而是尝试new Rectangle(Point.Empty, new Size(e.CellBounds.Width - 1, e.CellBounds.Height - 1)),看看是否可行。