结合一般自定义控件的答案:
custome child controls
和MSDN 模板控制
解决这个问题的正确方法非常简单,一旦在命名空间中创建和定义子元素(因为您需要交叉引用它),它应该有一个添加属性:Tab 类看起来像这样
namespace MyNS.Content {
public class Tab : System.Web.UI.UserControl
{
private string _title;
public Tab()
: this(String.Empty)
{
}
public Tab(string title)
{
_title = title;
}
public string Title
{
get { return _title; }
set { _title = value; }
}
private ITemplate tabContent = null;
[
TemplateContainer(typeof(TemplateControl)),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateInstance(TemplateInstance.Single),
]
public ITemplate TabContent
{
get
{
return tabContent;
}
set
{
tabContent = value;
}
}
}
}
这将允许 tabcontent 子标签进入您的主标签
在您的控件 ascx 中创建必要的 [ParseChildren(true, "MyTabs")] 并将您的 MyTabs 列表或集合绑定到转发器,这将输出所有包含的选项卡,您的 ascx 看起来像这样
<asp:repeater id="rpContent" runat="server" onitemdatabound="rpContent_itemdatabound">
<itemtemplate>
<asp:hyperlink id="hlHeader" runat="server" navigateurl="javascript://"></asp:hyperlink>
<div>
<asp:placeholder id="plTabContent" runat="server"></asp:placeholder>
</div>
</itemtemplate>
后面的代码是这样的
[ParseChildren(true, "MyTabs")]
public partial class KITT_controls_tabgroup : System.Web.UI.UserControl
{
private List<Tab> _myTabs;
[PersistenceMode(PersistenceMode.InnerProperty)]
public List<Tab> MyTabs
{
get
{
if (_myTabs == null)
{
_myTabs = new List<Tab>();
}
return _myTabs;
}
}
protected void Page_Load(object sender, EventArgs e)
{
rpContent.DataSource = MyTabs;
rpContent.DataBind();
}
protected void rpContent_itemdatabound(Object Sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Tab i = e.Item.DataItem as Tab;
i.TabContent.InstantiateIn(((PlaceHolder)e.Item.FindControl("plTabContent")));
((HyperLink)e.Item.FindControl("hlHeader")).Text = i.Title;
}
}
}
最后,注册您的控件(Tab 和 ascx)
<add tagPrefix="w" namespace="MyNS.Content" />
<add tagPrefix="KITT" tagName="TabbedContent" src="~/controls/tabbedcontent.ascx"/>
并使用它...
<kitt:tabbedcontent id="upgradedesktop" runat="server">
<w:Tab title="Overview" isdefault="true" runat="server">
<TabContent>
your html tags and server side tags here
</TabContent>
</w:Tab>
<w:tab title="Benefits" runat="server" >
<tabcontent>
your html tags and server side tags here
</tabcontent>
</w:tab>
<w:tab title="Products" runat="server">
<tabcontent>
your html tags and server side tags here
</tabcontent>
</w:tab>
</kitt:tabbedcontent>