答案是肯定的。
爲此,您應該創建一個類型,實現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