1

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

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

我怎么能说“20.50”应该出现在标签的右下角?

为了清楚起见,我用文字做了一个小例子:

在此处输入图像描述

我怎么能做到这一点?任何帮助表示赞赏!

4

2 回答 2

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;
于 2013-08-10T16:56:14.083 回答
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属性,然后在设计器中调整控件的大小并观察会发生什么!

于 2013-08-10T16:56:45.803 回答