How to add a new existing property to my control?

I have my own control:

public class newControl : Control { } 

The Text property exists, but the TextAlign property does not exist. For example, I need this property, similar to the TextAlign property for Button , but I do not want to inherit it from the button class.

So is it possible to inherit only the TextAlign property? If so, how?

0
source share
3 answers

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 have added some attributes for how the control is used in the PropertyGrid . The DefaultValue attribute does not set the value of the property; it simply determines whether the property is displayed in bold or not.

To display text using the TextAlign property, you will 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); } 
+3
source

First, consider inheritance from System.Web.UI.WebControls.WebControl , which has more properties that match the style, such as CssClass and Attributes .

Instead of using the TextAlign property TextAlign I would recommend simply adding a CSS class to your page and using the set CssClass property, which is located in the WebControl base class.

Alternatively, you can set the alignment of the text by following these steps (but the CSS class will be cleaner):

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

Of course, you can always add your own property, which writes the correct CSS to the Attributes collection.

0
source

aaaa I think that is not at all, and it’s impossible dude. You cannot inherit property: D

-2
source

Source: https://habr.com/ru/post/972210/


All Articles