集合属性相信大家都很熟悉也很常用,如DropDownList,ListBox等控件
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>测试1</asp:ListItem>
<asp:ListItem>测试2</asp:ListItem>
<asp:ListItem>测试3</asp:ListItem>
</asp:DropDownList>1.实现集合属性效果
经过前面几篇的学习,相信这一篇看起来已经相对简单了.我们要做的就是,先定义一个复杂属性,然后用迭代语句获取数组数据即可.
如果看过前面几篇就看看下面代码吧,相信看起来很简单,我们模仿一个DropDownList,为其属性添加背景属性,代码如下
先定义一个集合属性,如下
public class DropItem
{
private string text;
private string value;
private Color backColor;
[
Category("Behavior"),
DefaultValue(""),
Description("项文本"),
NotifyParentProperty(true),
]
public String Text
{
get
{
return text;
}
set
{
text = value;
}
}
[
Category("Behavior"),
DefaultValue(""),
Description("项值"),
NotifyParentProperty(true),
]
public String Value
{
get
{
return value;
}
set
{
this.value = value;
}
}
[
Category("Behavior"),
DefaultValue(""),
Description("背景颜色"),
NotifyParentProperty(true),
]
public Color BackColor
{
get
{
return backColor;
}
set
{
backColor = value;
}
}
}然后自定义一个控件,输出集合属性,如下代码
[ParseChildren(true, "DropItemList")]
public class DropColor:WebControl
{
private ArrayList dropItemList;
[
Category("Behavior"),
Description("项集合"),
DesignerSerializationVisibility(
DesignerSerializationVisibility.Content),
PersistenceMode(PersistenceMode.InnerDefaultProperty),
]
//定义集合属性
public ArrayList DropItemList
{
get
{
if (dropItemList == null)
{
dropItemList = new ArrayList();
}
return dropItemList;
}
}
//重写标签
protected override HtmlTextWriterTag TagKey
{
get
{
return HtmlTextWriterTag.Select;
}
}
protected override void RenderContents(HtmlTextWriter writer)
{
//输出集合属性
foreach (DropItem item in dropItemList)
{
DropItem dr = item as DropItem;
if (dropItemList != null && dropItemList.Count > 0)
{
//颜色转换
WebColorConverter wcc = new WebColorConverter();
writer.AddAttribute(HtmlTextWriterAttribute.Value, dr.Value.ToString());
writer.AddStyleAttribute(HtmlTextWriterStyle.BackgroundColor, wcc.ConvertToString(dr.BackColor));
writer.RenderBeginTag(HtmlTextWriterTag.Option);
writer.Write(dr.Text.ToString());
writer.RenderEndTag();
}
}
base.RenderContents(writer);
}
}上面代码注意颜色类型之间的转换,以下为HTML代码
<custom:DropColor ID="DropColor1" runat="server" ForeColor="White">
<custom:DropItem BackColor="Yellow" Text="黄色" Value="yellow" />
<custom:DropItem BackColor="Red" Text="红色" Value="red" />
<custom:DropItem BackColor="Blue" Text="蓝色" Value="blue" />
<custom:DropItem BackColor="Green" Text="绿色" Value="green" />
<custom:DropItem BackColor="Black" Text="黑色" Value="Black" />
</custom:DropColor>输出以后的效果如下图

效果还不错吧,而且挺实用的.