【问题标题】:How to set auto size the dynamic label box text in c#? [closed]如何在c#中设置自动调整动态标签框文本的大小? [关闭]
【发布时间】:2016-01-27 07:16:23
【问题描述】:

我已尝试遵循代码,我的问题已传递给标签文本,问题大小比标签文本长,因此无法在标签框中查看完整问题。请解决这个错误。

Label dynamiclabel = new Label();
dynamiclabel.Location = new Point(38, 30);
dynamiclabel.Size = new Size(200, 32);
dynamiclabel.Name = "lbl_ques";
dynamiclabel.Text = question;               
dynamiclabel.AutoSize = true;
dynamiclabel.Size = new System.Drawing.Size(900, 26);
dynamiclabel.Font = new Font("Arial", 12, FontStyle.Regular);

【问题讨论】:

  • 链接与我的问题无关。
  • 当 AutoSize=true 时,设置大小没有意义。它根据需要水平增长,但如果没有足够的空间也无济于事。要创建多行设置 AutoSize=false 并使其更高..
  • 但是我已经动态地创建了标签框。当我设置 label.AutoSize=false 时,标签中显示的问题的一半。你能写示例代码吗? @TaW41
  • 是的。你能告诉更多关于布局的信息吗?发布应该是什么的图像总是非常有帮助的。如果您无法将其添加到问题中,您可以将其上传到一些免费的字段上传服务.. - 标签是否位于父母的内部?有足够的空间吗?它们应该是多行的吗?

标签: c# winforms


【解决方案1】:

简答:

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 + "?";
}

如果您想使容器大小动态化,只需对 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();
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多