简答:
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();
}
这将调整所有问题标签的布局..: