你可注意VS中属性栏里有如下一些属性形式,红色标记部分:
属性描述:
一般属性:
下拉列表属性:
树状属性:
那么它们是怎么简单地实现的呢?答案就在下面,
1.属性描述
属性描述包含在属性定义的开头,"[.....]"一段代码中.
代码:
[ Bindable( true ), // 是否显示在属性栏中 Category( " Appearance " ), // 属性的分类,Appearance表示将此属性显示在"外观"栏中 DefaultValue( "" ), // 属性的默认值 Description( " 设置或获取BaseControl类型 " ) // 属性栏下方的描述 ] public virtual ControlType Type ... { //属性的定义部分 }2.一般属性
代码:
[属性描述] public string Title ... { get ...{ object o = ViewState["Title"]; if (o == null) return String.Empty; return (string)o; } set ...{ ViewState["Title"] = value; } }如果只想让属性为只读的话,只需写get语句就行了.如果属性是只读的,它在属性栏中显示灰色.
3.下拉列表属性
此中属性要定义一个枚举类型.
代码:
public enum ControlType ... { Label=0, TextBox=1, DatePicker=2 } public class BaseControl : WebControl, INamingContainer ... { ...... [属性描述] public virtual ControlType Type ...{ get ...{ object _type = ViewState["Type"]; if (_type == null) return ControlType.TextBox; else return (ControlType)_type; } set ...{ ViewState["Type"] = value; } } ...... }
4.树状属性
我们先给子属性定义的类.
代码:
public class LabelTextBox : Control ... { private SizeInfo _size; [Browsable(true), Description("获取和设置控件的大小"), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true), Category("Appearance") ] public virtual SizeInfo Size ...{ get ...{ if (_size == null) _size = new SizeInfo(); return _size; } } ...... } [TypeConverter( typeof (ExpandableObjectConverter))] public class SizeInfo ... { private int _width; private int _height; [NotifyParentProperty(true)] public int Width ...{ get ...{ return _width; } set ...{ _width = value; } } [NotifyParentProperty(true)] public int Height ...{ get ...{ return _height; } set ...{ _height = value; } } }这里的属性用另外一种方式写的,建议还是用第一种方式写比较好.
关于属性的定义写的不够全面,论述的不够深入,由于笔者学浅,请多多提出宝贵意见.
