今天可以说是费了九牛二虎之力, 通宵一晚, 才研究出这个webcontrol的collection属性的设置.
首先介绍几个属性上的attribute
1、DesignerSerializationVisibility
常用的是DesignerSerializationVisibility(DesignerSerializationVisibility.Content),表示要Render的是其内容,而非本身。
2、Editor
当属性使用的是ArrayList,而非一些强类型的属性,则需要有一个类继承System.ComponentModel.Design.CollectionEditor,用来确定设计时的界面
3、PersistenceMode
PersistenceMode.InnerProperty,指的是把该属性以内部tag的形式保存起来,而非保存到本控件的属性上。
4、NotifyParentProperty
NotifyParentProperty(true),表示当属性改变时,通知其父控件
原代码如下:
using System;
using System.Collections;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Web.UI;
using System.Drawing.Design;
namespace ClassLibrary2
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
[ParseChildren(true)]
public class MyWebControl : WebControl
{
private ArrayList myParam;
public MyWebControl()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
NotifyParentProperty(true),
Editor(typeof(MyCollectionEditor),typeof(UITypeEditor)),
PersistenceMode(PersistenceMode.InnerProperty)
]
public ArrayList MyParam
{
get
{
if(myParam == null) myParam = new ArrayList();
return myParam;
}
}
}
[TypeConverter(typeof(ExpandableObjectConverter))]
public class Parame
{
private string sss = "";
[NotifyParentProperty(true)]
public string SSS
{
get{return sss;}
set{sss=value;}
}
public Parame()
{
}
public override string ToString()
{
return sss;
}
}
public class MyCollectionEditor : System.ComponentModel.Design.CollectionEditor
{
public MyCollectionEditor(System.Type type):base(type)
{
}
protected override Type CreateCollectionItemType()
{
return typeof(Parame);
}
protected override bool CanSelectMultipleInstances()
{
return false;
}
}
}
其中最值得注意的,就是这一段
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
NotifyParentProperty(true),
Editor(typeof(MyCollectionEditor),typeof(UITypeEditor)),
PersistenceMode(PersistenceMode.InnerProperty)
]
public ArrayList MyParam
{
get
{
if(myParam == null) myParam = new ArrayList();
return myParam;
}
}
}
属性前的说明就不用多说,让我一直头痛了很久的就是,当我设置了有set的时候,即
public ArrayList MyParam
{
get
{
if(myParam == null) myParam = new ArrayList();
return myParam;
}
set
{
myParam = value;
}
}
这时候就会出现"创建控件时出错"的错误, 非得要把set去掉才成功, 很奇怪。如果真的是这样子,是否代表我就不能够使用MyControl.MyParam = xxx这样子的语句了?