您的位置:首页 > 编程语言

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

2007-07-26 22:50 567 查看
[ 来源]http://www.joyblog.cn/article.asp?id=47
组件的一些公共属性不希望被VS在设计时加到InitializeComponent()方法中怎么处理呢?我试过了,将属性加上[Browsable(false)]也不行。
我的代码如下:
public class CommunicationTypeComboBox : ComboBox

将控件放到窗体上,VS回自动在InitializeComponent()方法中加入一下代码。粗体部分。

//
// cmbCommunicationType
//
this.cmbCommunicationType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbCommunicationType.FormattingEnabled = true;
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);

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

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

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

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

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

[DesignOnly(false)]
public new ObjectCollection Items

2006-9-15 日更新

终极及解决方案

[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
public new ObjectCollection Items
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: