为什么Visual Studio会生成此代码?

时间:2014-03-17 17:25:29

标签: c# visual-studio-2010 combobox windows-forms-designer

我扩展了ComboBox对象,我想为它赋值。

每次都是相同的值,不允许在运行时更改。

这是我的目标:

public class TimesComboBox: ComboBox
{
    //These items' values are copied from PARC View
    private readonly Dictionary<String, TimeSpan> CONSTANTS = new Dictionary<string, TimeSpan>()
    {
        {"3 H", new TimeSpan(0,3,0,0,0)},
        {"8 H", new TimeSpan(0,8,0,0,0)},
        {"12 H", new TimeSpan(0,12,0,0,0)},
        {"1 D", new TimeSpan(1,0,0,0,0)},
        {"3 D", new TimeSpan(3,0,0,0,0)},
        {"7 D", new TimeSpan(7,0,0,0,0)},
        {"30 D", new TimeSpan(30,0,0,0,0)}
    };

    public TimesComboBox()
        : base()
    {
        DataSource = CONSTANTS.Keys.ToList();
    }

当我运行代码时,程序会抛出错误:

Items collection cannot be modified when the DataSource property is set.

并指出我使用TimesComboBox的表单的设计者:

// 
// timesComboBox1
// 
this.timesComboBox1.DataSource = ((object)(resources.GetObject("timesComboBox1.DataSource")));
this.timesComboBox1.FormattingEnabled = true;
this.timesComboBox1.Items.AddRange(new object[] {
"3 H",
"8 H",
"12 H",
"1 D",
"3 D",
"7 D",
"30 D"});
this.timesComboBox1.Location = new System.Drawing.Point(72, 55);
this.timesComboBox1.Name = "timesComboBox1";
this.timesComboBox1.Size = new System.Drawing.Size(121, 21);
this.timesComboBox1.TabIndex = 63;

在我看来,设计师正在生成试图两次添加项目的代码。它为什么这样做?我认为该列表只会在运行时分配给DataSource,那么为什么Visual Studio会在此之前生成代码呢?

1 个答案:

答案 0 :(得分:1)

这是因为控件类的构造函数也在设计时运行。这将设置DataSource Items属性,它们的值将像通常属性一样被序列化。所以你在Designer.cs代码中看到它们。通常是看不见的,而不是像它在这种情况下那样产生异常。

您告诉设计器序列化程序不要使用[DesignerSerializationVisibility]属性执行此操作:

[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new ObjectCollection Items {
    get { return base.Items; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new object DataSource {
    get { return base.DataSource; }
    set { base.DataSource = value;  }
}

添加[Browsable(false)]属性也会在“属性”窗口中隐藏该属性,很可能你也会想要这个属性。