Skip to main content
 首页 » 编程设计

c#之将文本设置到标签的右下边缘

2024年02月13日13qq78292959

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

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

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

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

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

请您参考如下方法:

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

将这个类添加到一个新文件中,构建您的项目,然后将这个控件放到您的窗体上。确保同时设置 Text 和 Text2 属性,然后在设计器中调整控件大小,看看会发生什么!