2016-07-07 50 views
-3

我有面板,每個面板都有1個標籤。一切工作正常,除了1兩件事: 我可以在面板高度不適合標籤的高度...使面板高度符合標籤高度

我使用這個代碼:

 Point location = new Point(0, 0); 
     ColorConverter cc = new ColorConverter(); 

     foreach (var item in temp) 
     { 
      Panel pan = new Panel(); 
      pan.AutoSize = false; 
      pan.Width = this.Width-75; 
      pan.Location = location; 
      pan.BackColor = (Color)cc.ConvertFromString("#" + item.Item3); 
      Label lbl = new Label(); 
      lbl.Font = new Font("Arial", 12); 
      lbl.ForeColor = Color.White; 
      lbl.Text = item.Item2; 
      lbl.AutoSize = true; 
      lbl.MaximumSize = new Size(pan.Width - 5, 0); 
      lbl.Width = pan.Width - 10; 
      lbl.Location = new Point(lbl.Location.X + 5, lbl.Location.Y + 5); 
      //pan.Height = lbl.Height + 5; 
      pan.Controls.Add(lbl); 
      flowLayoutPanel1.Controls.Add(pan); 
      location = new Point(location.X - pan.Height, location.Y); 
     } 

我試着這樣做:

pan.Height = lbl.Height + 5; 

但它的面板是那麼的方式太小......

+3

難看到了完全可以使用面板。只是不要,你不必解決這個問題。 –

+0

@HansPassant我需要一個 – ioncodes

+0

您可以嘗試在面板中停放標籤,將面板AutoSize設置爲true,並將AutoSizeMode設置爲GrowAndShrink。然後,您可以將面板填充設置爲5.這樣您就不必擔心標籤的大小或位置。 – Kinetic

回答

0

你可以嘗試在面板對接標籤,面板的AutoSize爲true,並設置AutoSizeMode設置爲GrowAndShrink。然後你可以將面板填充設置爲5.這樣你就不必擔心標籤的大小或位置

foreach (var item in temp) 
{ 
    Panel pan = new Panel(); 
    pan.Padding = new Padding(5); 
    pan.AutoSize = true; 
    pan.AutoSizeMode = AutoSizeMode.GrowAndShrink; 
    pan.BackColor = (Color)cc.ConvertFromString("#" + item.Item3); 
    Label lbl = new Label(); 
    lbl.Dock = DockStyle.Fill; 
    lbl.Font = new Font("Arial", 12); 
    lbl.ForeColor = Color.White; 
    lbl.Text = item.Item2; 
    lbl.AutoSize = true; 
    lbl.MaximumSize = new Size(pan.Width - 5, 0); 
    pan.Controls.Add(lbl); 
    flowLayoutPanel1.Controls.Add(pan); 
    location = new Point(location.X - pan.Height, location.Y); 
} 

編輯:忘了填充。

+0

哪條線將標籤「貼」到面板上?編輯:沒想到你編輯 – ioncodes

+0

它缺少填充和停靠線。我已經添加到我的答案。 – Kinetic

+0

你爲什麼評論2行?如果我這樣做,也會產生很多小的立方體。另外,如何將面板寬度設置爲固定的,如果它是自動調整的? – ioncodes

2

在我看來,您正在使用面板以在FlowLayoutPanel中的標籤周圍獲得邊距。如果是這種情況,設置標籤的保證金來代替,而沒有使用面板:

lbl.Margin = new Padding(5, 5, 80, 5); 

lbl.Margin = new Padding(5); // If all margins are equal 

的構造函數聲明如下

public Padding(int left, int top, int right, int bottom) 

public Padding(int all) 
+2

或者只是 '新Padding(5)' 如果左,上,右和底部都相等。 – Kinetic