TableLayoutPanel的行/列着色(vs2008,winform)

gau*_*kar 9 visual-studio-2008 winforms

我可以在TableLayoutPanel中为整个Row或Column添加特定颜色吗?怎么样 ?如果有的话请提供示例代码..

谢谢你.

Jay*_*ggs 21

是的你可以.

使用TableLayoutPanel的CellPaint事件来测试哪个行/列调用了事件,然后使用Graphic对象大小来设置矩形以设置单元格的颜色.

像这样(第一行和第三行):

     private void Form_Load(object sender, EventArgs e) {
        this.tableLayoutPanel1.CellPaint += new TableLayoutCellPaintEventHandler(tableLayoutPanel1_CellPaint);
     }


    void tableLayoutPanel1_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
    {
        if (e.Row == 0 || e.Row == 2) {
            Graphics g = e.Graphics;
            Rectangle r = e.CellBounds;
            g.FillRectangle(Brushes.Blue, r);
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 你想确保你丢弃刷子.将其创建包装在using(){}语句中或使用静态Brushes.Blue.否则你会在每个油漆上泄漏内存. (4认同)

Ale*_*ipt 5

我发现这个答案更容易实现:

这让我可以在我的手机上放一个完整的背景色.

  1. 创建一个Panel有背景色的,和
  2. DockPanel在我的TableLayoutPanel

那个TableLayoutPanelCell有一个背景颜色.

我的代码最终看起来像这样:

Panel backgroundColorPanel = new Panel();
backgroundColorPanel.BackColor = Color.FromArgb(243, 243, 243);
backgroundColorPanel.Dock = DockStyle.Fill;
backgroundColorPanel.Margin = new Padding(0);
backgroundColorPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left));
backgroundColorPanel.AutoSize = true;
backgroundColorPanel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.originalTableLayoutPanel.Controls.Add(backgroundColorPanel, 0, row);
Run Code Online (Sandbox Code Playgroud)

http://www.codeguru.com/forum/showthread.php?t=444944

  • 这有效,但在所需的代码行数、内存使用或处理器周期方面效率不高。 (2认同)