【问题标题】:Possible to have a inner control on a custom server control?可以在自定义服务器控件上有内部控件吗?
【发布时间】:2010-10-11 14:54:24
【问题描述】:

我希望能够做类似的事情:

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

还能做到:

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

我最终想出的答案代码:

[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
{
}

【问题讨论】:

    标签: asp.net custom-controls custom-server-controls asp.net-controls asp.net-customcontrol


    【解决方案1】:

    ParseChildren 属性告诉 .NET 是将控件的子项视为属性还是控件。对于您的第一个示例,您希望将孩子视为控件,因此添加

    [ ParseChildren(ChildrenAsProperties = false) ]
    

    对于第二个,您需要 ChildrenAsProperties=true,以及 ITemplate 类型的 TabTemplate 属性。之后涉及到一些管道,this MSDN sample 对此进行了描述。但是,如果您只需要一个模板,它不会增加很多价值。

    【讨论】:

    • 我粘贴了到目前为止的内容。几乎……:P
    猜你喜欢
    • 1970-01-01
    • 2011-04-13
    • 2014-06-11
    • 1970-01-01
    • 2013-07-31
    • 2010-11-02
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多