What should I do if I don’t want some public properties of a component to be added to the InitializeComponent() method by VS during design? I've tried adding [Browsable(false)] to the attribute but it doesn't work either.
My code is as follows:
/// <summary>
/// Controller communication type drop-down list box.
/// </summary>
public class CommunicationTypeComboBox : ComboBox
{
/// <summary>
/// Construct a list box instance.
/// </summary>
public CommunicationTypeComboBox()
{
Items.Add("Serial Port");
Items.Add("TCP");
}
/// <summary>
/// Get all items in the list box.
/// </summary>
[Browsable(false)]
public new ObjectCollection Items
{
get { return base.Items; }
}
}
Place the control on the form, and VS will automatically add some code to the InitializeComponent() method. Bold part.
//
// cmbCommunicationType
//
this.cmbCommunicationType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbCommunicationType.FormattingEnabled = true;
this.cmbCommunicationType.Items.AddRange(new object[] {
"serial port",
"TCP"});
this.cmbCommunicationType.Location = new System.Drawing.Point(124, 66);
this.cmbCommunicationType.Name = "cmbCommunicationType";
this.cmbCommunicationType.SelectedItem = Xunmei.Door.CommunicationType.SerialPort;
this.cmbCommunicationType.Size = new System.Drawing.Size(121, 20);
this.cmbCommunicationType.TabIndex = 2;
this.cmbCommunicationType.SelectedIndexChanged += new System.EventHandler(this.cmbCommunicationType_SelectedIndexChanged);
It will become like this as the number of edits increases. Is there a way around this other than not adding items in the constructor?
this.cmbCommunicationType.Items.AddRange(new object[] {
"serial port",
"TCP",
"serial port",
"TCP",
"serial port",
"TCP",
"serial port",
"TCP",
"serial port",
"TCP"});
After several days of hard work, I finally found the DesignOnlyAttribute class.
Specifies whether a property can only be set at design time.
Members marked by setting the DesignOnlyAttribute to true can only be set at design time. Typically, these properties only exist at design time and do not correspond to an actual property on the runtime object.
Members that have no attributes (Attribute) or are marked by setting DesignOnlyAttribute to false can be set at run time. The default is false.
Adding DesignOnlyAttribute to the Items attribute of CommunicationTypeComboBox can perfectly solve this problem.
/// <summary>
/// Get all items in the list box.
/// </summary>
[DesignOnly(false)]
public new ObjectCollection Items
{
get { return base.Items; }
}