[C #] Mom no longer needs to worry about how to add default values to special types of attributes with a custom GroupBox,

Source: Internet
Author: User

[C #] Mom no longer needs to worry about how to add default values to special types of attributes with a custom GroupBox,

------------------ Updated: 201411190903 ------------------

After thinking and practice, it is found that the 1st entries in the routine are unnecessary, that is, you do not need to define a field or attribute named Default + attribute name, you only need to implement the Reset and ShouldSerialize methods. There should be relevant documentation on these two methods, and indeed, find the statement on MSDN: http://msdn.microsoft.com/zh-cn/library/53b8022e (v = vs.80). aspx

------------------ Original: 201411182108 ------------------

What is the title, but it can really express my mood after mastering this method.

When writing a custom control, you often need to specify a default value for the Property (that is, you can right-click the property in VS and reset it). If the property type is a built-in value type, use the DefaultValue feature directly, for example:

[DefaultValue(false)]public bool CanSelect{    get;    set;}

The type that can be converted according to the String constant is also good, you can do this:

[DefaultValue (typeof (Font), ", 9pt")] public Font TitleFont {get; set ;}

However, in this case, the 2nd DefaultValue parameter must beString constantIt cannot be a variable, field, attribute, or method return value. Whether a type can be converted from a string depends on the implementation in the conversion class specified by the TypeConverter feature of the type. For more information about TypeConverter, see:

Http://msdn.microsoft.com/zh-cn/library/system.componentmodel.typeconverter (v = vs.80). aspx

Back to the question, then the question arises. What should I do if I want TitleFont's default value to be SystemFonts. DefaultFont? I just learned a trick. The following is an example of a custom control:

/// <Summary> /// enhanced GroupBox /// </summary> /// <remarks> /// Author: AhDung // Update: 201411181832, you can set the title Color and Font independently. // </remarks> public class GroupBoxEx: GroupBox {static Font defaultTitleFont; // define a static field // <summary> // default title Font /// </summary> public static Font DefaultTitleFont // encapsulate this static field, in fact, fields can be directly used without encapsulation, but the field name must be DefaultXXX {get {return defatititlefont ?? (DefaultTitleFont = SystemFonts. defaultFont) ;}} Color titleColor; /// <summary> /// obtain or set the title Color /// </summary> [Description ("retrieve or set the title Color")] [DefaultValue (typeof (Color), "0, 70,213")] public Color TitleColor {get {return titleColor;} set {if (titleColor! = Value) {titleColor = value; this. invalidate () ;}} Font titleFont; /// <summary> /// obtain or set the title Font /// </summary> [Description ("retrieve or set the title Font")]
Public Font TitleFont {get {return titleFont;} set {titleFont = value ?? DefaultTitleFont; // prevent attribute from being set to null this. invalidate () ;}/// <summary> // reset the title Font /// </summary> [EditorBrowsable (EditorBrowsableState. never)] protected virtual void ResetTitleFont () // implements a method to reset the default attribute value. The name must be ResetXXX {this. titleFont = null; // The property setter contains null processing} // <summary> // whether to explicitly set the title Font // </summary> [EditorBrowsable (EditorBrowsableState. never)] protected virtual bool ShouldSerializeTitleFont () // real A Method to indicate whether to write the attribute value to the Form Designer file. The name must be ShouldSerializeXXX {return! TitleFont. equals (defatititlefont);} // <summary> // re-paint // </summary> protected override void OnPaint (PaintEventArgs e) {if (Application. renderWithVisualStyles & (Width> = 10) & (Height> = 10) {TextFormatFlags flags = TextFormatFlags. preserveGraphicsTranslateTransform | TextFormatFlags. preserveGraphicsClipping | TextFormatFlags. textBoxControl | TextFormatFlags. wordBreak; if (! This. showKeyboardCues) {flags | = TextFormatFlags. hidePrefix;} if (this. rightToLeft = RightToLeft. yes) {flags | = TextFormatFlags. rightToLeft | TextFormatFlags. right;} GroupBoxRenderer. drawGroupBox (e. graphics, this. clientRectangle, this. text, this. titleFont, this. enabled? This. TitleColor: SystemColors. ControlDark, flags, this. Enabled? System. windows. forms. visualStyles. groupBoxState. normal: System. windows. forms. visualStyles. groupBoxState. disabled);} else {base. onPaint (e) ;}/// <summary> // initialize the control /// </summary> public GroupBoxEx () {SetStyle (ControlStyles. allPaintingInWmPaint | ControlStyles. userPaint | ControlStyles. optimizedDoubleBuffer, true); titleColor = Color. fromArgb (0, 70,213); ResetTitleFont (); // call the reset method directly to initialize the attribute value }}

Note: the intention of writing this control is to make the title of GroupBox conspicuous under NT6. NT5 is highlighted in blue by default, but NT6 is black, which is not so conspicuous and affects the program experience. Although you can directly set the ForeColor and Font attributes of GroupBox to achieve the goal, but in this case, the child control in it will inherit, and you have to change these two attributes of the Child control back ~ It hurts. Therefore, in order to independently set the color and font of the title of GroupBox, the Custom Attributes TitleColor and TitleFont are added, and the default value of TitleFont is set to SystemFonts. defaultFont encountered a problem in this article. After several searches, I read some useful posts, later, I got a positive result from the source code of the Control class (the above example references the standard practice in the Control class). Now that we have solved the problem, I want to share the methods and controls with you. There is nothing to say about the control implementation. The following describes how to specify the default value for properties of unconventional types.

The following describes how to use the property whose type is Font and whose name is TitleFont in the preceding control:

-To have a field or attribute of the same type, the name must be "Default +", that is, "DefaultTitleFont" and "static. Assign the desired default value to this field/attribute. In this example, SystemFonts. DefaultFont is used. It can be seen that it is not as painful as DefaultValue can only assign values to built-in values or string constants. You can assign values at will ~ Or a ball.

-To implement a Reset + attribute name without any parameters and return method, that is, ResetTitleFont (). The function of this method is to re-assign the attribute to the default value. In this example, because the setter of the attribute is processed, that is, if the value is null, it is replaced with the default value. Therefore, it is not necessary to assign the value null directly. If the setter does not have this processing, it needs to assign the value to the above defaulttitlefon ~ Remember. The modifier does not matter. The modifier is public virtual in Control. This example is protected virtual, considering that this method does not need to be called externally. The [EditorBrowsable (EditorBrowsableState. Never)] feature is used to prevent this method from appearing in the VS smart prompt when using controls. This is also the practice in Control. Obviously, this method is used by the designer, not by the designer ~ Eye-catching

-Then implement a ShouldSerialize + attribute name method. If there is no parameter, return bool. ShouldSerializeTitleFont (). This method is related to serialization in terms of words. I did not test serialization and do not know whether it is related, but it must be related to whether to write the default value to the Designer file of the form, that is, the file automatically generated by VS for the form that contains the InitializeComponent () method. If this method is not used, you cannot reset the attribute. The logic of the method is that if the value assigned to the attribute is the default value, it tells VS not to explicitly assign a value to the attribute in InitializeComponent. It should be noted that if true is returned, the value must be explicitly assigned. Therefore, pay attention to the logic when writing the return of this method. The modifier is the same as the Reset method.

-The final step is to assign an initial value to the attribute in the constructor. Because the Reset method does this, this method is called directly in this example. This is not a Control method. The Control constructor does not see the call to the Reset method, but there are a lot of processing, including calling some internal methods, so it is too lazy to trace them, I have never tried whether or not to assign the initial value is a problem. For the sake of insurance, I still assigned it. In addition, the default value specified by DefaultValue is simply right-click in VS, and the default value is no longer explicitly assigned to InitializeComponent, at the same time, the value in PropertyGrid is no longer explicitly in bold, it does not mean that the initial value of the attribute has been set to the value specified by defavalue value. In this example, although defavalue is specified for TitleColor, however, if titleColor = Color is not initialized in the constructor. fromArgb (0, 70,213), The TitleColor value will be default (Color), that is, Color. empty, so do not forget to assign the initial value after DefaultValue is used. Remember that DefaultValue is not responsible for the assignment. But will the Reset method be the same? I have never tried it. I guess it will not automatically assign the initial value. After all, Initialization is the work of the constructor, and VS is more powerful and intelligent, it is also unlikely that a Reset will automatically insert a Reset to the constructor ~ Not suitable or scientific. So to be safe, I still assigned TitleFont to the constructor.

Finally, let's take a look at the results:

Before skin whitening:

After skin whitening:

-Wen Bi-

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.