将文本设置为标签的最右边缘?

时间:2013-08-10 16:37:29

标签: c# winforms label

简单的例子,假设我正在创建一个像这样的标签:

Label label = new Label();
label.Text = "Hello" + "20.50";
label.Width = 250;
label.Height = 100;
panel1.Controls.Add(label);

我怎么能说“20.50”应出现在标签的最右边?

为了清楚起见,我在单词中做了一个小例子:

enter image description here

我怎么能实现这个目标?任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:2)

以下是您需要的自定义标签:

public class CustomLabel : Label
{
    public CustomLabel()
    {
        TopLeftText = BottomRightText = "";
        AutoSize = false;
    }
    public string TopLeftText {get;set;}        
    public string BottomRightText {get;set;}                
    protected override void OnPaint(PaintEventArgs e)
    {
        using (StringFormat sf = new StringFormat() { LineAlignment = StringAlignment.Near})
        {
            using(SolidBrush brush = new SolidBrush(ForeColor)){
              e.Graphics.DrawString(TopLeftText, Font, brush, ClientRectangle, sf);
              sf.LineAlignment = StringAlignment.Far;
              sf.Alignment =  StringAlignment.Far;
              e.Graphics.DrawString(BottomRightText, Font, brush, ClientRectangle, sf);
            }
        }
    }
}
//use it:
//first, set its size to what you want.
customLabel1.TopLeftText = house.Name;
customLabel2.BottomRightText = house.Number;

答案 1 :(得分:2)

使用Label控件没有内置支持。您需要从Label继承以创建自定义控件,然后自己编写绘图代码。

当然,您还需要一些方法来区分这两个字符串。应用于两个字符串时,+符号是连接符号。这两个字符串由编译器连接在一起,所以你得到的就是:Hello20.50。您将需要使用两个单独的属性,每个属性都有自己的字符串,或者在两个字符串之间插入某种分隔符,以后可以将它们分开。由于你已经在创建一个自定义控件类,我会使用单独的属性 - 更清晰的代码,更难以出错。

public class CornerLabel : Label
{
   public string Text2 { get; set; }

   public CornerLabel()
   {
      // This label doesn't support autosizing because the default autosize logic
      // only knows about the primary caption, not the secondary one.
      // 
      // You will either have to set its size manually, or override the
      // GetPreferredSize function and write your own logic. That would not be
      // hard to do: use TextRenderer.MeasureText to determine the space
      // required for both of your strings.
      this.AutoSize = false;
   }

   protected override void OnPaint(PaintEventArgs e)
   {
      // Call the base class to paint the regular caption in the top-left.
      base.OnPaint(e);

      // Paint the secondary caption in the bottom-right.
      TextRenderer.DrawText(e.Graphics,
                            this.Text2,
                            this.Font,
                            this.ClientRectangle,
                            this.ForeColor,
                            TextFormatFlags.Bottom | TextFormatFlags.Right);
   }
}

将此类添加到新文件,构建项目,然后将此控件放到表单上。确保同时设置TextText2属性,然后调整设计器中的控件大小并观察会发生什么!