在自定义控件的构建(1)中曾提到WebControl在浏览器中被渲染为,如果需要,可以重写TagKey指定其它的标签
下面的例子,用
namespace MyControls
{
///
/// 重写TagKey属性生成自定义的标签
///
public class Glow : WebControl
{
public Glow()
{
this.Width = Unit.Parse("500px");
}
public string Text
{
get; set;
}
protected override HtmlTextWriterTag TagKey
{
get { return HtmlTextWriterTag.Div; }
}
protected override void RenderContents(HtmlTextWriter writer)
{
writer.Write(Text);
}
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
writer.AddStyleAttribute(HtmlTextWriterStyle.Filter, "glow(Color=#ffd700,Strength=10)");
base.AddAttributesToRender(writer);
}
}
}
该控件重写了基类的TagKey属性,所以查看源码是渲染成
上面的代码注意一下AddAttributesToRender(),一旦重写了该方法,就可以为控件生成的开始标签添加HTML和CSS特性。
运行:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>title>
head>
<body>
<form id="form1" runat="server">
<fullrender:Glow ID="Glow2" runat="server" Text="Hello!" />
form>
body>
html>
构建组合控件
如果不需要从头设计一个控件,那么可以考虑构建组合控件。
在ASP.NET中每个控件都暴露了Controls属性表示其所包含的所有子控件。
这里利用TextBox和RequiredFieldValidator控件构建一个组合控件
namespace MyCompositeControls
{
///
/// 构建组合控件
///
public class RequiredTextBox : CompositeControl
{
private TextBox inputbox;
private RequiredFieldValidator vaildator;
public string Text
{
get
{
EnsureChildControls();
return inputbox.Text;
}
set
{
EnsureChildControls();
inputbox.Text = value;
}
}
protected override void CreateChildControls()
{
inputbox = new TextBox();
inputbox.ID = "input";
this.Controls.Add(inputbox);
vaildator = new RequiredFieldValidator();
vaildator.ID = "valInput";
vaildator.ControlToValidate = inputbox.ID;
vaildator.ErrorMessage = "No blank";
vaildator.Display = ValidatorDisplay.Dynamic;
this.Controls.Add(vaildator);
}
}
}
可以看出,RequiredTextBox从CompositeControl基类继承而来,并且重写了CreateChildControls()。
这里属性Text的get与set都调用了EnsureChildControls(),其强制调用CreateChildControls(),但是会避免对CreateChildControls()多次调用,如果
试图在调用CreateChildControls()之前使用Text属性,就会得到一个空引用,必须先创建子控件才能访问子控件的属性。
下面的代码展示了如何使用该控件:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>title>
head>
<body>
<form id="form1" runat="server">
<div>
<composite:RequiredTextBox ID="RequiredTextBox" runat="server"/>
<asp:Button ID="Button1" runat="server" Text="单击" />
div>
form>
body>
html>
如果把Trace设为true的话,可以看到RequiredTextBox包含了TextBox和RequiredFieldValidator两个控件
本文参考引用了《ASP.NET 3.5揭秘(卷2)》这本书
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/25284529/viewspace-684565/,如需转载,请注明出处,否则将追究法律责任。
![user_pic_default.png](http://blog.itpub.net/images/user_pic_default.png)
<%=items[i].content%>
<%if(items[i].items.items.length) { %><%=items[i].items.items[j].username%> 回复 <%=items[i].items.items[j].tousername%>: <%=items[i].items.items[j].content%>
转载于:http://blog.itpub.net/25284529/viewspace-684565/