答案是肯定的。
为此,您应该创建一个类型,实现ITemplate
接口并在其中添加一个自定义属性/属性(我在示例中添加了属性Name
);还添加了一个继承自Collection<YourTemplate>
的类。
这里是做的一个例子:
public class TemplateList : Collection<TemplateItem> { }
public class TemplateItem : ITemplate
{
public string Name { get; set; }
public void InstantiateIn(Control container)
{
var div = new HtmlGenericControl("div");
div.InnerText = this.Name;
container.Controls.Add(div);
}
}
和控制自己:
[ParseChildren(true, "Templates"), PersistChildren(false)]
public class TemplateLibrary : Control
{
public TemplateLibrary()
{
Templates = new TemplateList();
}
[PersistenceMode(PersistenceMode.InnerProperty)]
public TemplateList Templates { get; set; }
protected override void RenderChildren(HtmlTextWriter writer)
{
foreach (var item in Templates)
{
item.InstantiateIn(this);
}
base.RenderChildren(writer);
}
}
最后使用的例子:
<my:TemplateLibrary runat="server">
<my:TemplateItem Name="hello" />
<my:TemplateItem Name="there" />
</my:TemplateLibrary>
顺便说一句,你也可以用它作为:
<my:TemplateLibrary runat="server">
<Templates>
<my:TemplateItem Name="hello" />
<my:TemplateItem Name="there" />
</Templates>
</my:TemplateLibrary>
效果会一样。
嗨。当我尝试从铭牌继承我得到一个味精“类只能从其他类继承”谢谢 – 2011-06-30 12:26:09
@Yisman,假设你在'VB'下,应该使用'实现'而不是'继承'(因为这是一个接口)。 – Alex 2011-06-30 13:34:34
也许我错过了一些东西,但是这段代码会生成ITemplate对象(所谓的自定义类型),它*不具有在它们下面构建的标记控制树?实现一个自定义的'InstantiateIn'类* *击败了标记模板的重点。 – 2012-09-20 01:47:27