How can I add new existing property to my control?

半世苍凉 提交于 2019-12-25 14:06:21

问题


I have my own control:

public class newControl : Control
{
}

There is a Text property, but there is not a TextAlign property. For example, I need this property similar to the TextAlign property of a Button, but I don't want inherit it from a button class.

So can I inherit only TextAlign property? If yes, how?


回答1:


Yes, you can just add it. The built in enumeration is called 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; }
  }
}

What you do with this property is up to you now.

Note that I added some attributes for how the control is used in the PropertyGrid. The DefaultValue attribute does not set the value of the property, it just determines whether or not the property is displayed in bold or not.

To display the text using your TextAlign property, you would have to override the OnPaint method and draw it:

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



回答2:


First, consider inheriting from System.Web.UI.WebControls.WebControl, which has more properties that correspond to styling, such as CssClass and Attributes.

Rather than using the TextAlign property, I would recommend simply adding a CSS class to your page, and use set CssClass property, which is on the base class WebControl.

Alternatively, you could set the text alignment by doing the following (but a CSS class would be cleaner):

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

Of course, you could always add your own property that writes the correct CSS to the Attributes collection as well.




回答3:


aaaa I think generally no and it is impossible dude .You can not inherit a property :D



来源:https://stackoverflow.com/questions/8927800/how-can-i-add-new-existing-property-to-my-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!