組件的一些公共屬性不希望被VS在設(shè)計(jì)時(shí)加到InitializeComponent()方法中怎么處理呢?我試過了,將屬性加上[Browsable(false)]也不行。
我的代碼如下:
/// <summary>
/// 控制器通訊類型下拉列表框。
/// </summary>
public class CommunicationTypeComboBox : ComboBox
{
/// <summary>
/// 構(gòu)造列表框?qū)嵗?BR> /// </summary>
public CommunicationTypeComboBox()
{
Items.Add("串口");
Items.Add("TCP");
}
/// <summary>
/// 獲取列表框中的所有項(xiàng)。
/// </summary>
[Browsable(false)]
public new ObjectCollection Items
{
get { return base.Items; }
}
}
將控件放到窗體上,VS回自動(dòng)在InitializeComponent()方法中加入一下代碼。粗體部分。
//
// cmbCommunicationType
//
this.cmbCommunicationType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbCommunicationType.FormattingEnabled = true;
this.cmbCommunicationType.Items.AddRange(new object[] {
"串口",
"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);
隨著編輯次數(shù)的增會(huì)變成這樣。除了不在構(gòu)造函數(shù)中增加項(xiàng)以外,有沒有辦法解決這個(gè)問題?
this.cmbCommunicationType.Items.AddRange(new object[] {
"串口",
"TCP",
"串口",
"TCP",
"串口",
"TCP",
"串口",
"TCP",
"串口",
"TCP"});
經(jīng)過幾天的努力終于找到了DesignOnlyAttribute 類 。
指定某個(gè)屬性 (PRoperty) 是否只能在設(shè)計(jì)時(shí)設(shè)置。
通過將 DesignOnlyAttribute 設(shè)置為 true 進(jìn)行標(biāo)記的成員只能在設(shè)計(jì)時(shí)進(jìn)行設(shè)置。通常,這些屬性 (Property) 只能在設(shè)計(jì)時(shí)存在,并且不對應(yīng)于運(yùn)行時(shí)對象上的某個(gè)實(shí)際屬性 (Property)。
沒有屬性 (Attribute) 或通過將 DesignOnlyAttribute 設(shè)置為 false 進(jìn)行標(biāo)記的成員可以在運(yùn)行時(shí)進(jìn)行設(shè)置。默認(rèn)為 false。
將CommunicationTypeComboBox的Items屬性加上DesignOnlyAttribute 就可以完美解決該問題。
/// <summary>
/// 獲取列表框中的所有項(xiàng)。
/// </summary>
[DesignOnly(false)]
public new ObjectCollection Items
{
get { return base.Items; }
}
新聞熱點(diǎn)
疑難解答
圖片精選