Summary of properties, events, and some related attributes in a custom control in C #

Source: Internet
Author: User

Today, I learned about the next C # User control development event that adds custom properties, mainly referencing MSDN, summarizing and experimenting with features (Attribute) for developing custom properties and events.

Here's my environment first:

Operating system: Windows7 flagship version (Service Pack 1)

VS version: Microsoft Visual Studio Ultimate 2012, version 11.0.50727.1 Rtmrel

. NET Framework Version: 4.5.50938

C # version: Visual C # 2012

First, the preparatory work

1, build a C # form application, the main form is named FormMain, and then add a user control to the solution named Testusercontrol

2, put a button in the Testusercontrol, named Btntest

3. When the control is done, it will appear in the Toolbox

4, drag the control to a form (forms) can be used, named TestUserControl1. The name is vs default, that is, the first letter lowercase, and the last number as the ordinal.

Second, add custom attributes

In the Testusercontrol class, add the following code:

<summary>///button name///</summary>public string buttonname{get {//todo return btntest.t    Ext    } set {//todo btntest.text = value; }}

Once the code has been added, the TestUserControl1 attribute added to the formmain will appear btnname

Iii. Adding custom events

In the Testusercontrol class, add the following code:

<summary>///events///</summary>public event EventHandler btntestclick;///<summary>///Test button//< /summary>///<param name= "sender" ></param>///<param name= "E" ></param>private void     btnTest_Click (object sender, EventArgs e) {if (Btntestclick! = null) {//todo Btntestclick (sender, E); }}

After the code is added, the TestUserControl1 event that is added to the FormMain will appear Btntestclick

Implement this function in the code of FormMain

private void Testusercontrol1_btntestclick (object sender, EventArgs e) {MessageBox.Show (sender. ToString () + "\ r \ n" + e.tostring ());}

Then run the program, click on the Control testUserControl1 button btntest, there will be the following effect:

Four, several characteristics (Attribute)
1) defaultevent and Defaultproperty: Specify Default events and default properties for custom controls

Defaulteventattribute (MSDN) can be used to specify default events for components, such as adding code to the Testusercontrol class

[DefaultEvent ("Btntestclick")]

In the form editing interface, double-clicking the control testUserControl1 will automatically enter the Testusercontrol1_btntestclick event.

Here again, the System.Windows.Forms.Control class code in C # is as follows:

[classinterface (Classinterfacetype.autodispatch) [ ComVisible (True)][defaultevent ("click")][defaultproperty ("Text")][designer (" System.windows.forms.design.controldesigner, system.design, version=4.0.0.0, culture=neutral, &NBSP;PUBLICKEYTOKEN=B03F5F7F11D50A3A ")][designerserializer (" System.windows.forms.design.controlcodedomserializer, system.design, version=4.0.0.0, culture= neutral, publickeytoken=b03f5f7f11d50a3a ", " system.componentmodel.design.serialization.codedomserializer, system.design, version=4.0.0.0,  CULTURE=NEUTRAL,&NBSP;PUBLICKEYTOKEN=B03F5F7F11D50A3A ")][toolboxitemfilter (" System.Windows.Forms ")]public  class control : component, idroptarget, isynchronizeinvoke, iwin32window,  ibindablecomponent, icomponent, idisposable{ /* ... */ } 

Here you can see that the value of the defaultevent is "click", which is why the button is dragged into the form, and after the double-click it enters its Click event:

private void Button1_Click (object sender, EventArgs e)

For a control that does not want to use the Click event as the default event, you manually specify the DefaultEvent attribute of the control, such as the Declaration of a check box (checkbox):

[ClassInterface (Classinterfacetype.autodispatch)] [ComVisible (True)] [Defaultbindingproperty ("CheckState")] [DefaultEvent ("CheckedChanged")] [Defaultproperty ("Checked")] [ToolboxItem ("System.windows.forms.design.autosizetoolboxitem,system.design, version=4.0.0.0, Culture=neutral, PUBLICKEYTOKEN=B03F5F7F11D50A3A ")]public class checkbox:buttonbase{/* ... */}

Here the DefaultEvent is written "Checkedchange", so in the form of the editing interface, double-click the check box when the default entry of the edit event is

private void Checkbox1_checkedchanged (object sender, EventArgs e)

Custom controls (directly inherit from UserControl), if you do not add this property, the event entered after double-clicking on the edit interface is the Load event.

Similar features as Defaultproperty,defaultpropertyattribute (MSDN) can be used to specify the default properties of a component. When you specify a default property, the property is automatically selected in the Property browser window when the user clicks the control in the form:

[Defaultproperty ("Btnname")]
2) browsable: Sets whether a property or event of a control appears in the Properties window

BrowsableAttribute (MSDN) Specifies whether a property or event should be displayed in the Properties window, such as adding code on the property Btnname:

[Browsable (False)]

The control TestUserControl1 's property interface will not have btnname settings, the red line is the location of the previous Btnname

If a property or event does not have the browsable attribute added, the property or event can also be seen in the Properties window. It is also explained here that browsable can only determine the visibility of a property or event within the Properties window, browsable properties and events that are set to false, and can still be used in the editor through code.

3) Description: Specifies the caption of a property or event in a control that appears in the Properties window

DescriptionAttribute (MSDN) Specifies the description of a property or event that appears in the Properties window for a control

For example, add the following code to the Btnname:

[Description ("Set the text displayed on the button")]

can also be used with the browsable feature:

[Browsable (True)] [Description ("Set the text displayed on the button")]

Or write in a pair of parentheses, separated by commas:

[Browsable (True), Description ("Set the text displayed on the button")]

The explanatory text you see in the properties interface looks like this:

4) Editorbrowsable: Specifies that a property or method is visible in the editor

Editorbrowsableattribute (MSDN) specifies that a property or method can be viewed in the editor.

The Editorbrowsableattribute constructor is as follows:

Public Editorbrowsableattribute (editorbrowsablestate state);

Where Editorbrowsablestate is an enumeration (enum) with a total of three values, namely always, never, and advanced

Always: The property or method is still browsable in the editor

Never: The property or method cannot always be browsed in the editor

Advanced: This property or method is a feature that is visible only to the senior user. The editor can show or hide these properties

The first two are good to understand, the third advanced will really make people confused (what is called "Senior users"? )。 Then I looked up some information before I knew the visibility of advanced members can be configured in options under the Tools menu.

(here thanks to the great God's answer on social.msdn.microsoft.com)

If "Hide advanced Members" is checked, the properties marked with the Code "[Editorbrowsable (editorbrowsablestate.advanced)]" will not be automatically displayed in the IDE. But this is only not automatic display, if the code is really called the Invisible Property, the compilation will not error, the operation will not be a problem.

such as: Btnname is marked as "Editorbrowsablestate.never", so this property does not appear in the smart hint of VS (called IntelliSense), but if written in the code, there is no problem.

It is important to note that this concealment is only valid if the control code is not visible to the current solution, that is, if the implementation code of the control is within your solution, Editorbrowsable does not guarantee that the user will not see this property. However, if the control is placed in a DLL file to add references to the current solution, the Editorbrowsable attribute can function as described in its text description.

5) DesignerSerializationVisibility: How the code generator generates component-related code

DesignerSerializationVisibilityAttribute (MSDN) is used to specify the type of persistence to use when serializing properties on a component at design time.

Parameter is an enumeration of type designerserializationvisibility:

Hidden: Code generator does not generate code for objects

Visible: Code generated by code generator object

Content: Code generator produces object content code, not code of the object itself

This statement seemed to be difficult to understand at one glance, so I decided to use two specific examples to illustrate:

1, hidden and visible, content of the difference

or with our Btnname attribute above as an example, the argument is "Designerserializationvisibility.hidden"

[DesignerSerializationVisibilityAttribute (Designerserializationvisibility.hidden)]public string BtnName{get {    return btntest.text;    } set {btntest.text = value; }}

Drag the control into the FormMain form designer, which you can see in the file FormMain.Designer.cs:

The

Changes the DesignerSerializationVisibilityAttribute parameter of the attribute above btnname to "designerserializationvisibility.visible" or " Designerserializationvisibility.content, the code in the function InitializeComponent () will be different:

The <summary>///Designer supports the required method-do not use the Code Editor to modify the contents of this method.    </summary>private void InitializeComponent () {this.testusercontrol1 = new Controltest.testusercontrol (); This.    SuspendLayout ();    TestUserControl1//This.testUserControl1.BtnName = "Button1";    This.testUserControl1.Location = new System.Drawing.Point (36, 32);    This.testUserControl1.Name = "TestUserControl1";    This.testUserControl1.Size = new System.Drawing.Size (134, 77);    This.testUserControl1.TabIndex = 0; // ...}

As you can see, the difference is the following line of code:

This.testUserControl1.BtnName = "Button1";

Use of hidden is not, using the visible will be (using the content will also have)

With hidden, in the properties interface, regardless of how the value of the Btnname property is modified, the compiler ignores the value at compile time and uses the default value (in this case, the Button1). With hidden, this line of code will disappear after the program has been recompiled, even if the code assigned to the above line is manually added to the FormMain.Designer.cs.

2. The difference between visible and content

Content is used in collections that can be serialized, such as the System.Windows.Forms.DataGridView Class (data table)

Summary://Gets a collection that contains all the columns in the control. Returns the result://A System.Windows.Forms.DataGridViewColumnCollection that contains all the columns in the system.windows.forms.datagridview//control. [DesignerSerializationVisibility (Designerserializationvisibility.content)] [Editor ("System.Windows.Forms.Design.DataGridViewColumnCollectionEditor, System.Design, version=4.0.0.0, culture= Neutral, publickeytoken=b03f5f7f11d50a3a ", typeof (UITypeEditor))][mergableproperty (false)]public DataGridViewColumnCollection Columns {get;}

The IDE simply generates the code for those properties that contain the component, without generating the code for the property itself. When you use the IDE to add individual datagridviewtextboxcolumn, The code for each datagridviewtextboxcolumn will be placed in the FormMain.Designer.cs file, and the Columns property itself will only generate such a piece of code in the function InitializeComponent ():

This.dataGridView1.Columns.AddRange (New system.windows.forms.datagridviewcolumn[] {this. Column1,this. Column2,this. COLUMN3});
6) Other features

Many other features (such as localizable are used to specify whether a property is localizable, DefaultValue is used to specify another "default" for a property, and so on), such as just a preliminary understanding of how to view vs from an assembly The declarations and summaries of each control, control property, control event that is reflected in System.Windows.Forms.dll (the green Word above), and a more detailed description can refer to MSDN.

END

Summary of properties, events, and some related attributes in a custom control in C #

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.