如何为派生控件的属性设置默认值?

时间:2012-01-31 14:38:20

标签: c# winforms inheritance controls default-value

我从ToolStripComboBox派生,以创建一个封装百分比选取下拉列表。目标是在派生控件中进行所有验证和字符串解析。当选择的百分比发生变化时,父母只会收到一个事件,并且可以访问公共整数来获取和设置百分比。

我遇到的问题是,在我将派生控件放在父控件的设计器文件中,它会不断使用ComboBox.Items.AddRange方法添加一整套字符串。在我的派生控件的构造函数中,我有以下内容:

foreach (int i in percentages)
{
    ComboBox.Items.Add(String.Format("{0}%", i));
}

随着时间的推移,这些值会在设计器文件中累积很多次。我不知道如何隐藏Items属性,因为它不是虚拟的。我想抑制我的设计器文件泛滥。

我的设计师档案示例:

this.zoom_cbo.Items.AddRange(new object[] {
"10%",
"25%",
"50%",
"75%",
"100%",
"150%",
"200%",
"300%",
"400%",
"600%",
"800%",
"1600%",
"10%",
"25%",
"50%",
"75%",
"100%",
"150%",
"200%",
"300%",
"400%",
"600%",
"800%",
"1600%",
"10%",
"25%",
"50%",
"75%",
"100%",
"150%",
"200%",
"300%",
"400%",
"600%",
"800%",
"1600%",
"10%",
"25%",
"50%",
"75%",
"100%",
"150%",
"200%",
"300%",
"400%",
"600%",
"800%",
"1600%",
"10%",
"25%",
"50%",
"75%",
"100%",
"150%",
"200%",
"300%",
"400%",
"600%",
"800%",
"1600%",
"10%",
"25%",
"50%",
"75%",
"100%",
"150%",
"200%",
"300%",
"400%",
"600%",
"800%",
"1600%",
"10%",
"25%",
"50%",
"75%",
"100%",
"150%",
"200%",
"300%",
"400%",
"600%",
"800%",
"1600%"});

2 个答案:

答案 0 :(得分:1)

也许只有当你不处于设计模式时才应该进行添加,例如:

if (this.DesignMode)
{
  // design time only stuff
}
else
{
  // runtime only stuff.
  foreach (int i in percentages)
  {
    ComboBox.Items.Add(String.Format("{0}%", i));
  }
}

答案 1 :(得分:1)

由于它是用户只是选择的派生列表,请尝试将其添加到派生的组合框以防止序列化项目:

[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new ObjectCollection Items
{
  get { return ((ComboBox)this).Items; }
}