【问题标题】:Update text in WinForms Label symmetrically from center从中心对称更新 WinForms 标签中的文本
【发布时间】:2020-04-21 12:20:12
【问题描述】:
WinFormsLabel控件中的文本如何从中心对称更新,如果这里的每一行都是值更新,而不是单个文本,先显示“A”,然后显示“New”等:
A
New
Year
Comes
again
and again
to spread
the spirit and
Celebration have
a wonderful New Year
party and Happy New Year
with joy and peace
【问题讨论】:
标签:
c#
winforms
label
text-alignment
【解决方案1】:
您可以将标签AutoSize设置为false,让它们具有相同的宽度和相同的左侧:
foreach(var lbl in labels)
{
lbl.SuspendLayout();
lbl.Left = 0;
lbl.Width = 500;
lbl.TextAlign = ContentAlignment.MiddleCenter;
lbl.ResumeLayout();
}
为了获得所有标签,你可以
var labels = parent.Controls.OfType<Label>().ToList();
//where parent is the container of the labels
// note that this would select any other label on the container
您也可以手动添加它们:
Label[] labels = new[] {label1, label2, ....};
【解决方案2】:
使用 StringBuilder,标签的 TextAlign 属性设置为 MiddleCenter,AutoSize 设置为 true。
StringBuilder sb = new StringBuilder();
sb.AppendLine("A");
sb.AppendLine("New");
sb.AppendLine("Year");
sb.AppendLine("Comes");
sb.AppendLine("again");
sb.AppendLine("and again");
sb.AppendLine("to spread");
sb.AppendLine("the spirit and");
sb.AppendLine("Celebration have");
sb.AppendLine("a wonderful New Year");
sb.AppendLine("party and Happy New Year");
sb.AppendLine("with joy and peace");
Label l = new Label();
l.AutoSize = true;
l.TextAlign = ContentAlignment.MiddleCenter;
l.Text = sb.ToString();
Controls.Add(l);
【解决方案3】:
具有TextAlign = MiddleCenter 的单个标签就可以解决问题。只需确保不要在每行文本之前或之后放置额外的空格:
label1.AutoSize = true;
label1.TextAlign = ContentAlignment.MiddleCenter;
label1.Text =
@"
A
New
Year
Comes
again
and again
to spread
the spirit and
Celebration have
a wonderful New Year
party and Happy New Year
with joy and peace
";
【讨论】:
-
label1.Text = "A"; 然后 label1.Text += "New\n"; 或 label1.Text += "New"+Environment.NewLine; 等等。如果您还希望在添加文本行之间有延迟,您可以这样做like this。