如何在c#中设置自动调整动态标签框文本的大小?

时间:2016-01-27 07:16:23

标签: c# winforms

我试过跟随代码,我的问题传递给标签文本,问题大小比标签文本长,所以无法在标签框中查看完整的问题。请解决这个错误。

executePost(serviceURL,loginParams.toString());

1 个答案:

答案 0 :(得分:0)

简短回答:

dynamiclabel.MaximumSize = new System.Drawing.Size(900, 26);

说明:最好的方法是使用AutoSize = true和合适的MaximumSize的组合:表单或容器中的布局将设置允许Labels的宽度限制成长。如果你不控制它,它们将无限制地增长。所以设置这个限制,考虑到滚动条,填充,边距和一些松弛的空间将给你在MaximumSize属性中使用的数字。

让我们在FlowLayoutPanel中添加几个问题,以便最简单的布局:

for (int q = 0; q < 50; q++) addQuestion(flowLayoutPanel1, q + 1);

以下是创建由两个标签组成的问题的例程:

void addQuestion(FlowLayoutPanel flp, int nr)
{
    Label l1 = new Label();
    l1.AutoSize = true;
    l1.Font = new System.Drawing.Font("Consolas", 9f, FontStyle.Bold);
    l1.Text = "Q" + nr.ToString("00") + ":";
    l1.Margin = new System.Windows.Forms.Padding(0, 5, 10, 0);
    flp.Controls.Add(l1);

    Label l2 = new Label();
    l2.Text = randString(50 + R.Next(150));
    l2.Left = l1.Right + 5;
    l2.AutoSize = true;
    l2.Margin = new System.Windows.Forms.Padding(0, 5, 10, 0);
    // limit the size so that it fits into the flp; it takes a little extra
    l2.MaximumSize = new System.Drawing.Size(flp.ClientSize.Width - 
           l2.Left - SystemInformation.VerticalScrollBarWidth  - l2.Margin.Right * 2, 0);
    flp.Controls.Add(l2);
    flp.SetFlowBreak(l2, true);
}

我使用一个小的随机字符串生成器:

Random R = new Random(100);
string randString(int len)
{
    string s = "";
    while (s.Length < len) s+= (R.Next(5) == 0) ? " " : "X";
    return s.Length + " " + s + "?";
}

enter image description here

如果你想使容器化动态只需编码resize事件来调整问题的MaximumSize

private void flowLayoutPanel1_Resize(object sender, EventArgs e)
{
    flowLayoutPanel1.SuspendLayout();
    int maxWidth = flowLayoutPanel1.ClientSize.Width  - 
                   SystemInformation.VerticalScrollBarWidth ;
    foreach (Control ctl in flowLayoutPanel1.Controls )
    {
        if (ctl.MaximumSize.Width != 0)
           ctl.MaximumSize = new Size(maxWidth - ctl.Left - ctl.Margin.Right * 2, 0);
    }
    flowLayoutPanel1.ResumeLayout();
}

这将调整所有问题标签的布局..:

enter image description here