使面板高度适合标签高度

本文关键字:高度 标签 | 更新日期: 2023-09-27 17:56:05

我有面板,每个面板都有 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;

但是面板太小了...

使面板高度适合标签高度

在我看来

,您正在使用面板来获取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)

您可以尝试将标签停靠在面板中,将面板"自动大小"设置为"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);
}

编辑:忘记填充。