Possible to have a inner control on a custom server control?

一世执手 提交于 2019-12-11 07:49:40

问题


I would like to be able to do something like:

<ui:Tab Title="A nice title">
  <TabTemplate>
    <asp:Literal runat="server" ID="SetMe">With Text or Something</asp:Literal>
  </TabTemplate>
</ui:Tab>

but also be able to do:

<ui:Tab Title="A nice title">
  <TabTemplate>
    <asp:DataList runat="server" ID="BindMe"></asp:DataList>
  </TabTemplate>
</ui:Tab>

Answer code I eventually came up with:

[ParseChildren(true)]
public class Node : SiteMapNodeBaseControl, INamingContainer
{
    private ITemplate tabTemplate;
    [Browsable(false),
    DefaultValue(null),
    Description("The tab template."),
    PersistenceMode(PersistenceMode.InnerProperty),
    TemplateContainer(typeof(TabTemplate))]
    public ITemplate TabTemplate
    {
        get { return tabTemplate; }
        set { tabTemplate = value; }
    }
    protected override void CreateChildControls()
    {
        if (TabTemplate != null)
        {
            Controls.Clear();
            TabTemplate i = new TabTemplate();
            TabTemplate.InstantiateIn(i);
            Controls.Add(i);
        }
    }
    protected override void Render(HtmlTextWriter writer)
    {
        EnsureChildControls();
        base.Render(writer);
    }
}


public class TabTemplate : Control, INamingContainer
{
}

回答1:


The ParseChildren attribute tells .NET whether to treat your control's children as properties or as controls. For your first example, you want to treat children as controls, so add

[ ParseChildren(ChildrenAsProperties = false) ]

For the second, you want ChildrenAsProperties=true, and a TabTemplate property of type ITemplate. There's some plumbing involved after that, which this MSDN sample describes. It doesn't add a lot of value if you only need one template, though.



来源:https://stackoverflow.com/questions/616560/possible-to-have-a-inner-control-on-a-custom-server-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!