ASP.NET用户控件内部内容

4
我有一个用户控件,它接受一个 title 属性。我也希望在该用户控件标记内部包含输入的 HTML(还包括 ASP 控件),如下所示:
<uc:customPanel title="My panel">
     <h1>Here we can add whatever HTML or ASP controls we would like.</h1>
     <asp:TextBox></asp:TextBox>
</uc:customPanel>

我该如何实现这个?我的title属性已经正常工作。
谢谢。

我认为你不能这样做...但是你可以在用户控件的.ascx中完成它。 - ACP
你能具体说明一下吗?我的ascx文件中有<%=title%>和<%=content%>,它们工作得很好,但是将自定义HTML传递给content属性非常麻烦。 - ademers
System.Web.UI.UserControl 没有 textbox 属性。 - ACP
您可以动态地向用户控件添加控件。 - ACP
1
为什么不将这些标签和其他内容放在用户控件自己的(ascx)文件中?或者这是一个自定义控件而不是实际的用户控件吗? - Stephen M. Redd
2个回答

7

实现一个扩展 Panel 类且实现 INamingContainer 接口的类:

public class Container: Panel, INamingContainer
{
}

然后,您的CustomPanel需要公开一个类型为Container的属性和另一个类型为ITemplate的属性:
public Container ContainerContent
{
    get
    {
       EnsureChildControls();
       return content;
    }
}
[TemplateContainer(typeof(Container))]
[TemplateInstance(TemplateInstance.Single)]
public virtual ITemplate Content
{
    get { return templateContent; }
    set { templateContent = value; }
}

然后在方法CreateChildControls()中添加以下内容:
if (templateContent != null)
{
    templateContent.InstantiateIn(content);
}

您将会像这样使用它:

<uc:customPanel title="My panel"> 
    <Content>    
        <h1>Here we can add whatever HTML or ASP controls we would like.</h1>
        <asp:TextBox></asp:TextBox>
     </Content>
</uc:customPanel>

0

你需要确保调用EnsureChildControls方法。有许多方法可以实现,例如通过CreateChildControls基本方法,但你可以简单地这样做来获取自定义控件的内部内容以进行呈现。当你需要记住状态和触发事件时,情况会变得更加复杂,但对于纯HTML,这应该可以工作。

protected override void Render(HtmlTextWriter writer) {
    EnsureChildControls();
    base.Render(writer);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接