C# 将面板高度调整到标签高度

C# 将面板高度调整到标签高度,c#,winforms,C#,Winforms,我有面板,每个面板都有一个标签。除了一件事外,一切正常: 我无法将面板高度与标签高度匹配 我正在使用以下代码: Point location = new Point(0, 0); ColorConverter cc = new ColorConverter(); foreach (var item in temp) { Panel pan = new Panel(); pan.Aut

我有面板,每个面板都有一个标签。除了一件事外,一切正常: 我无法将面板高度与标签高度匹配

我正在使用以下代码:

        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;

但是如果面板太小了…

您可以尝试将标签固定在面板中,将面板“自动调整大小”设置为true,并将“自动调整大小”设置为“增长和收缩”。然后可以将面板填充设置为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);
}

编辑:忘记了填充。

在我看来,您使用面板是为了在FlowLayoutPanel中的标签周围获得边距。如果是这种情况,请设置标签的边距,不要使用面板:

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

构造函数是这样声明的

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

public Padding(int all)

很难看出使用面板的意义。只要不这样做,您就不必解决这个问题。@HansPassant我需要一个您可以尝试将标签固定在面板中,将面板的“自动大小”设置为true,并将“自动大小模式”设置为“增长和收缩”。然后可以将面板填充设置为5。这样,您就不必担心标签的大小或位置了。我不知道该怎么做,xDI看不到您在设置面板高度。很难说你想要实现什么。请解释你的目标是什么。哪一行将标签“停靠”到面板上?编辑:无论您编辑什么编辑都缺少填充线和停靠线。我已经在我的答案中添加了这两行。你为什么评论这两行?如果我也这么做的话,它会产生很多小立方体。此外,如果面板自动调整大小,我如何将面板宽度设置为固定值?顺便说一句,我认为面板也没用,Olivier的答案是正确的。我真希望我知道你想要实现什么。或者,如果左、上、右和下都相等,我只需
新填充(5)
public Padding(int left, int top, int right, int bottom)

public Padding(int all)