简单的例子,可以说我正在创建一个这样的标签:

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


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

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



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

最佳答案

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属性,然后在设计器中调整控件的大小并观察会发生什么!

09-06 04:51
查看更多