微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

带有子项的ASP.NET自定义/用户控件

我想创建一个具有子项的自定义/用户控件.

例如,我希望我的控件具有以下标记

<div runat="server" id="div">
    <label runat="server" id="label"></label>
    <div class="field">
        <!-- INSERT CHILDREN HERE -->
    </div>
</div>

当我想在页面上使用它时,我只需:

<ctr:MyUserControl runat="server" ID="myControl">
    <span>This is a child</span>
    <div runat="server" id="myChild">And another <b>child</b>
</ctr:MyUserControl>

我的用户控件中的子控件将被插入到我的用户控件中.完成此任务的最佳方法是什么?

功能类似于asp:PlaceHolder,但我想添加更多选项以及其他标记等.此外,子控件仍然需要能够被页面访问. (在上面的例子中,页面上应该有myChild控件)

编辑——

它可以是模板控件,只要它允许我引用页面上的子项.

解决方法

我刚才问了类似的问题.见 here.

我相信你必须使用ITemplate作为InnerProperty:

[PersistenceMode(PersistenceMode.InnerProperty)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[TemplateInstance(TemplateInstance.Single)]
public ITemplate Content
{
    get
    {
        return _content;
    }
    set
    {
        _content = value;
    }
}
private ITemplate _content;

然后覆盖控件的CreateChildControls方法

protected override void CreateChildControls()
{
   if (this.Content != null)
   {
      this.Controls.Clear();
      this.Content.InstantiateIn(this);
   }
   base.CreateChildControls();
}

使用ITemplate有什么危害您可以将它与现有标记结合使用,并在Content属性中编写您想要的任何HTML.

原文地址:https://www.jb51.cc/aspnet/251365.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐