Right-aligned labels in WinForms

后端 未结 9 1453
甜味超标
甜味超标 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

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

提交回复
热议问题