【问题标题】:How can I add new existing property to my control?如何将新的现有属性添加到我的控件?
【发布时间】:2012-02-14 05:09:48
【问题描述】:

我有自己的控制权:

public class newControl : Control
{
}

Text 属性,但没有TextAlign 属性。例如,我需要这个类似于ButtonTextAlign 属性的属性,但我不想从按钮类继承它。

那么我可以只继承TextAlign 属性吗?如果是,怎么做?

【问题讨论】:

  • 从 ButtonBase 类继承会对您有帮助,或者您也不想这样做..否则您需要为 newControl 创建自己的公共属性..
  • 问题是我不想有很多不可用的属性等等。我当然看到ButtonBase class,它不适合我。我需要在我的控件中使用TextAlign 属性(具有正确的视觉效果),但我不需要边框样式(例如)等等......问题是如果可能的话,该怎么做我>。或者我需要找到已经包含我需要的所有东西的其他任何东西。感谢您的回答!

标签: c# winforms inheritance properties controls


【解决方案1】:

是的,您可以添加它。内置枚举称为ContentAlignment

using System.ComponentModel;
using System.Windows.Forms;

public class newControl : Control {

  private ContentAlignment _TextAlign = ContentAlignment.MiddleCenter;

  [Description("The alignment of the text that will be displayed on the control.")]
  [DefaultValue(typeof(ContentAlignment), "MiddleCenter")]
  public ContentAlignment TextAlign {
    get { return _TextAlign; }
    set { _TextAlign = value; }
  }
}

您现在如何处理此属性。

请注意,我在PropertyGrid 中添加了一些关于如何使用控件的属性。 DefaultValue 属性不设置属性的值,它只是确定属性是否以粗体显示。

要使用您的 TextAlign 属性显示文本,您必须重写 OnPaint 方法并绘制它:

protected override void OnPaint(PaintEventArgs e) {
  switch (_TextAlign) {
    case ContentAlignment.MiddleCenter: {
        TextRenderer.DrawText(e.Graphics, this.Text, this.Font, this.ClientRectangle, this.ForeColor, Color.Empty, 
                              TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
        break;
      }
    case ContentAlignment.MiddleLeft: {
        TextRenderer.DrawText(e.Graphics, this.Text, this.Font, this.ClientRectangle, this.ForeColor, Color.Empty,
                              TextFormatFlags.Left | TextFormatFlags.VerticalCenter);
        break;
      }
    // more case statements here for all alignments, etc.

  }
  base.OnPaint(e);
}

【讨论】:

  • 谢谢,很好!但是您知道如何将 Text 放在它上面精确的这个属性吗?可能这是一个有点愚蠢的问题,但我没有在我的控件中看到文本......如何让这个属性像按钮一样工作?附言.Text != "";
  • @justAuser 不确定我是否关注。您的意思是当您将控件放在表单上时,this.Text 不会出现在控件上?
  • @justAuser 我添加了代码来显示OnPaint 覆盖。由于这是 您的 自定义控件,因此您必须完成绘制您想要显示的内容的工作。
  • 非常感谢!我想这就是我要找的!现在我明白了它是如何工作的。)当我输入this.Text = "something"; 时,文本不会出现,我认为它必须出现在控件上)所以它可能会覆盖另一个类...
【解决方案2】:

首先考虑从System.Web.UI.WebControls.WebControl继承,它有更多与样式对应的属性,例如CssClassAttributes

我建议不要使用 TextAlign 属性,而是简单地向您的页面添加一个 CSS 类,并使用基类 WebControl 上的 set CssClass 属性。

或者,您可以通过执行以下操作来设置文本对齐方式(但 CSS 类会更简洁):

this.Attributes["style"] = "text-align: center";

当然,您也可以随时添加自己的属性,将正确的 CSS 写入 Attributes 集合。

【讨论】:

  • 但是我用的是WinForms...我觉得不合适。我只想控制我需要的东西,仅此而已。我可以继承Form 有很多好的属性,但我不需要很多...
  • 哦,我已经用winforms 标记了这个问题。我以为这是在网络上。
猜你喜欢
  • 1970-01-01
  • 2013-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-15
  • 2011-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多