如何让.Net控件在设计时InitializeComponent()中不生成相关代码

<script type="text/javascript"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<script type="text/javascript"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
组件的一些公共属性不希望被VS在 设计时加到InitializeComponent()方法中怎么处理呢?我试过了,将属性加上[Browsable(false)]也不行。
我的代码如下:
/// <summary>
/// 控制器通讯类型下拉列表框。
/// </summary>
public class CommunicationTypeComboBox : ComboBox
{
/// <summary>
/// 构造列表框实例。
/// </summary>
public CommunicationTypeComboBox()
{
Items.Add("串口");
Items.Add("TCP");
}

/// <summary>
/// 获取列表框中的所有项。
/// </summary>
[Browsable(false)]
public new ObjectCollection Items
{
get { return base.Items; }
}
}


控件放到窗体上,VS回自动在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);


随着编辑次数的增会变成这样。除了不在构造函数中增加项以外,有没有办法解决这个问题?

this.cmbCommunicationType.Items.AddRange(new object[] {
"串口",
"TCP",
"串口",
"TCP",
"串口",
"TCP",
"串口",
"TCP",
"串口",
"TCP"});

经过几天的努力终于找到了DesignOnlyAttribute 类 。
指定某个属性 (Property) 是否只能在设计时设置。

通过将 DesignOnlyAttribute 设置为 true 进行标记的成员只能在设计时进行设置。通常,这些属性 (Property) 只能在设计时存在,并且不对应于运行时对象上的某个实际属性 (Property)。

没有属性 (Attribute) 或通过将 DesignOnlyAttribute 设置为 false 进行标记的成员可以在运行时进行设置。默认为 false。

将CommunicationTypeComboBox的Items属性加上DesignOnlyAttribute 就可以完美解决该问题。

/// <summary>
/// 获取列表框中的所有项。
/// </summary>
[DesignOnly(false)]
public new ObjectCollection Items
{
get { return base.Items; }
}

<script type="text/javascript"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<script type="text/javascript"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值