【问题标题】:Building a templated ASP.NET control构建模板化 ASP.NET 控件
【发布时间】:2018-06-21 18:02:38
【问题描述】:

我正在玩一个使用 ASP.NET 模板系统的复合控件。

我希望能够在我的标记中定义HeaderTemplateFooterTemplate,并以编程方式在两者之间添加UserControl

我的目标是这样的:

<asp:DropZone runat="server" ID="LeftZone">
   <HeaderTemplate>
      <h1>Getting started</h1>
   </HeaderTemplate>
   <FooterTemplate>
      <h3>The end of it...</h3>
   </FooterTemplate>
</asp:DropZone>

我的 DropZone 类如下所示:

public class DropZone : Control, INamingContainer
{
    private ITemplate headerTemplate;
    private ITemplate footerTemplate;

   [DefaultValue((string)null), 
    Browsable(false), 
    PersistenceMode(PersistenceMode.InnerProperty), 
    TemplateInstance(TemplateInstance.Single)]
    public virtual ITemplate HeaderTemplate
    {
        get { return headerTemplate; }
        set { headerTemplate = value; }
    }

   [DefaultValue((string)null), 
    Browsable(false), 
    PersistenceMode(PersistenceMode.InnerProperty), 
    TemplateInstance(TemplateInstance.Single)]
    public ITemplate FooterTemplate
    {
        get { return footerTemplate; }
        set { footerTemplate = value; }
    }

    protected override void OnInit(EventArgs e)
    {
        EnsureChildControls();
        base.OnInit(e);
    }

    private void AppendTemplate(ITemplate template, Control container)
    {
        if (template == null) return;

        var ph = new PlaceHolder();
        container.Controls.Add(ph);
        template.InstantiateIn(ph);
    }

    protected override void CreateChildControls()
    {
        Controls.Clear();

        AppendTemplate(HeaderTemplate, this);

        Control helloWorld = Page.LoadControl("~/WebParts/HelloWorld.ascx");
        if (helloWorld != null)
        {
            Controls.Add(helloWorld);
        }

        AppendTemplate(FooterTemplate, this);

        ChildControlsCreated = true;
        base.CreateChildControls();
    }
}

但是,这不起作用,因为 ITemplate 字段永远不会被实例化。

任何帮助或指导将不胜感激。

更新:我必须从 CompositeControl 派生我的自定义控件才能让事情按预期工作。

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    【讨论】:

    • 谢谢。显然我必须从 CompositeControl 派生我的 DropZone 控件,而不仅仅是 Control - 现在一切都按预期工作。
    • 啊,是的。 CompositeControl 是你的朋友。
    • 你也可以只实现 INamingContainer 而不是复合控件。它是一个标记模板,以确保输出唯一的 id。 CompositeControl 就是这样做的,这就是它起作用的原因。
    猜你喜欢
    • 1970-01-01
    • 2011-02-23
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    相关资源
    最近更新 更多