Right-aligned labels in WinForms

后端 未结 9 1449
甜味超标
甜味超标 2021-01-07 15:59

The most obvious way to right-align a Label in WinForms doesn\'t work: setting anchor to Top/Bottom Right and TextAlign to TopRight. If the text changes the lab

相关标签:
9条回答
  • 2021-01-07 16:51

    Using a FlowLayoutPanel to do it works very well.

    flowLayoutPanel.FlowDirection = System.Windows.Forms.FlowDirection.RightToLeft;
    flowLayoutPanel2.Controls.Add(label);
    

    Then, just make sure that the flowLayoutPanel is large enough for the label to expand.

    0 讨论(0)
  • 2021-01-07 16:51

    Well as Sphax noticed you have to:

    1. Set AutoSize to false
    2. Set TextAlign to Right, for example to MiddleRight
    3. Resize label to real size using MeasureString

    Code:

    label.AutoSize = false; 
    label.TextAlign = ContentAlignment.MiddleRight;    
    
    int yourWidthHere = 100;    
    using (Graphics g = label.CreateGraphics())    
    {    
         SizeF size = g.MeasureString(text, label.Font, yourWidthHere);    
         label.Height = (int)Math.Ceiling(size.Height);    
         label.Text = text;    
    }   
    
    0 讨论(0)
  • 2021-01-07 16:52

    if you set the form property RightToLeft = yes; so you should not use the Text Align property just set the Anchor. try this approaches:

    Form.righttoleft = yes;
    label.anchor = Top, Right;
    label.TextAlign = TopLeft;
    

    or

    Form.righttoleft = No;
    label.anchor = Top, Right;
    label.TextAlign = TopRight;
    

    or

    Form.righttoleft = yes;
    label.righttoleft = No;
    label.anchor = Top, Right;
    label.TextAlign = TopRight;
    
    0 讨论(0)
提交回复
热议问题