控件,将用户输入的数据显示在控件中,效果图如下:

在这个控件中,我声明了一个集合属性Item供用户输入要显示的整型数值。我们按照WinForm控件制作教程(二)中的方法将控件加到ToolBox里,然后拖到Form设计器中,然后选中控件,在属性浏览中查看控件的属性,属性中有一个Item的属性,属性右边的值显示为Collection,当你点击这个值的时候,值的右边出现一个小按钮,点击这个小按钮,就会出现弹出一个Collection Editor窗口,你可以在在这个编辑器里添加你想显示的整型值,如图:
添加完以后,关闭Collection Editor。现在我们看看Form设计器为我们生成了什么代码。对于用户在Form设计器中设计的内容,设计器的代码生成器会将代码生成到窗口类的InitializeComponent()方法中,对于vs2005来说,这个方法位于***.Designer.cs文件中,在我当前的工程中位于Form1.Designer.cs文件中。在solution浏览器中双击打开这个文件,看看Form设计器为我们生成了什么代码:
//
// myListControl1
//
this.myListControl1.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
this.myListControl1.Item = ((System.Collections.Generic.List<int>)(resources.GetObject("myListControl1.Item")));
this.myListControl1.Location = new System.Drawing.Point(12, 34);
this.myListControl1.Name = "myListControl1";
this.myListControl1.Size = new System.Drawing.Size(220, 180);
this.myListControl1.TabIndex = 1;
this.myListControl1.Text = "myListControl1";

设计器将Item的内容串行化到了资源文件里。现在我们修改控件的代码,让设计器将Item的内容串行化到源代码里。我们为Item属性添加DesignerSerializationVisibilityAttribute,代码片断如下:
[Browsable(true)]
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Content)]
public List<Int32> Item

{
get

{
return _list;
}
set

{
_list = value;
}
}

编辑完以后,Build控件工程,回到测试工程里,将Item属性里的值,删掉重新添加,添加完以后,我们再来看看设计器生成的代码:
//
// myListControl1
//
this.myListControl1.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
this.myListControl1.Item.Add(1);
this.myListControl1.Item.Add(2);
this.myListControl1.Item.Add(3);
this.myListControl1.Item.Add(6);
this.myListControl1.Item.Add(8);
this.myListControl1.Item.Add(9);
this.myListControl1.Location = new System.Drawing.Point(12, 34);
this.myListControl1.Name = "myListControl1";
this.myListControl1.Size = new System.Drawing.Size(220, 180);
this.myListControl1.TabIndex = 1;
this.myListControl1.Text = "myListControl1";

现在设计器将Item的内容串行化到源代码里了。
时间有限,今天就写到这里,下一篇文章我来介绍TypeConverterAttribute。