从中心对称地更新 WinForms Label 中的文本

Update text in WinForms Label symmetrically from center

如何在 WinForms Label 控件中从中心对称地更新文本 如果这里的每一行都是值更新,而不是单个文本,首先显示 "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 

您可以将标签 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, ....}; 

使用 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);

具有 TextAlign = MiddleCenter 的单个标签就可以解决问题。只要确保您没有在每行文本之前或之后放置额外的 space:

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
";