c# - 构建模板化 ASP.NET 控件

标签 c# asp.net

我正在尝试使用 ASP.NET 模板系统的复合控件。

我希望能够在我的标记中定义一个 HeaderTemplate 和一个 FooterTemplate,并以编程方式在两者之间添加一个 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 控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1082409/

相关文章:

c# - 插入后更新 GridView

c# - 对如何在 C# 中使用 return 感到困惑

c# - 反序列化具有可变数量元素的 JSON 字符串

javascript - 单击时更改行颜色 - ASP.NET 和 JavaScript

c# - ASP.NET 列表框高度

c# - 使用 Linq 方法返回时间

c# - 带前导空格的确切字符数

C# 属性强制属性

javascript - 协调 ASP.NET 脚本包和源映射

c# - 使用 SvcUtil.exe 创建的服务引用托管 .NET 服务时出现问题 : XmlSerializer errors on Wrapped mode