2010-01-09 14 views

回答

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

你要確保你處置刷。將其創建包裝在using(){}語句中,或使用靜態Brushes.Blue。否則,你會泄漏每個油漆的內存。 – Eilon 2010-01-09 04:58:53

+0

感謝提醒,Eilon - 並提及選項使用靜態筆刷。 – 2010-01-09 05:20:05

+0

'Brushes.Blue'是一個靜態屬性,所以我不會處理它,否則下次使用它時可能會失效。 – 2014-11-21 19:14:24

5

我發現這個答案更容易實現:

這讓我把一個完整的背景色上我的手機。

  1. TableLayoutPanel

創建Panel,其中有一個背景色,並

  • DockPanel然後就是TableLayoutPanel細胞具有 背景色。

    我的代碼最終看上去像這樣:

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

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

  • +1

    這可行,但在所需的代碼行,內存使用情況或處理器週期方面效率不高。 – 2014-10-23 15:59:14