aBind();
}
通过Container数据绑定表达式获取容器对象属性,此处容器对象为默认的Article
如下实现
<custom:Article
id="Article1"
Runat="server">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<%# Container.Title%><br />
<%# Container.Author %><br />
<%# Container.Contents %><br />
</ItemTemplate>
</custom:Article>
好了,到这里你就实现了一个简单的动态模板控件了.
2.3 实现默认模板
在购书网站上我们常常看到由于图书太多的情况下,管理人员未能将图书封面发布到网站上,这时此书可能出现默认的图片"尚为此书添加图书封面"
在一个具有模板的控件里,如果你未为控件添加模板属性的话,你可以通过实现默认模板来实现默认效果.
(1)那你第一步要做的就是定义一个自定义模板.此模板需要实现ITemplate接口,实现InstantiateIn方法.看一下典型实现,如下代码
public class ArticleDefaultTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
Label lblTitle = new Label();
lblTitle.DataBinding += new EventHandler(lblTitle_DataBinding);
Label lblAuthor = new Label();
lblAuthor.DataBinding += new EventHandler(lblAuthor_DataBinding);
Label lblContents = new Label();
lblContents.DataBinding += new EventHandler(lblContents_DataBinding);
container.Controls.Add(lblTitle);
container.Controls.Add(new LiteralControl("<br />"));
container.Controls.Add(lblAuthor);
container.Controls.Add(new LiteralControl("<br />"));
container.Controls.Add(lblContents);
}
void lblTitle_DataBinding(object sender, EventArgs e)
{
Label lblTitle = (Label)sender;
ArticleWithDefault container = (ArticleWithDefault)lblTitle.NamingContainer;
lblTitle.Text = container.Title;
}
void lblAuthor_DataBinding(object sender, EventArgs e)
{
Label lblAuthor = (Label)sender;
ArticleWithDefault container = (ArticleWithDefault)lblAuthor.NamingContainer;
lblAuthor.Text = container.Author;
}
void lblContents_DataBinding(object sender, EventArgs e)
{
Label lblContents = (Label)sender;
ArticleWithDefault container = (ArticleWithDefault)lblContents.NamingContainer;
lblContents.Text = container.Contents;
}
}
在InstantiateIn方法中,定义了默认控件,并实现了默认绑定.在各自的数据绑定事件里通过容器控件(默认容器控件为ArticleWithDefault,此处还是没自定义容器控件,下面会介绍)的NamingContainer属性获取控件ID值.然后对控件进行赋值.
(2)重写CreateChildControls方法
当未定义模板属性时,则实现默认模板
protected override void CreateChildControls()
{
if (_itemTemplate == null)
_item
|