带内容模板的ASP.net自定义控件对我不起作用

时间:2014-05-01 05:16:35

标签: asp.net custom-controls contenttemplate

关于解决方案: ASP.Net: User control with content area, it's clearly possible but I need some details

我正在尝试做同样的事情,这是我的代码:

背后的控制代码:

[ParseChildren(true, "Content")]
[PersistChildren(false)]
public partial class SlidingPanelControl : System.Web.UI.UserControl
{
    protected override void OnInit(EventArgs e)
    {
        phContent.Controls.Add((Control)_content);
        base.OnInit(e);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    private PlaceHolder _content;
    [PersistenceMode(PersistenceMode.InnerProperty)]
    public PlaceHolder Content { get { return _content; } set { _content = value; } }
}

控制ASPX:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SlidingPanelControl.ascx.cs" Inherits="Photography.Controls.MbExtruder.SlidingPanelControl" %>
<div>
<asp:Panel ID="pnlLockable" runat="server" Visible="False">
    <asp:PlaceHolder runat="server" ID="phContent" />
</asp:Panel>
</div>

这就是我在主页中使用控件的方式:

<uc1:SlidingPanelControl runat="server" ID="SlidingPanelControl"
    Title="About" Position="right" Opacity="1" WidthInPixels="600">
    <Content><h1>hello world</h1></Content>
</uc1:SlidingPanelControl>

这对我不起作用,它没有将html渲染到控件占位符中。虽然当我调试控件的OnInit时,我可以看到_content控件具有我设置的所有html(在此示例中为<h1>Hello World</h1>

任何猜测我做错了什么?

由于

1 个答案:

答案 0 :(得分:0)

好的,所以我在我的电脑上查了一下,我找到了真正有用的解决方案:

[ParseChildren(false)]
[PersistChildren(false)]
public partial class WebUserControl1 : System.Web.UI.UserControl
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        if (Content != null)
        {
            ContentContainer container = new ContentContainer();
            Content.InstantiateIn(container);
            phContent.Controls.Add(container);
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

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

public class ContentContainer : Control, INamingContainer
{
}

我自己检查了它的魅力。其他来源的代码与您的相同。