【问题标题】:Error in Web User Control with ITemplate in the Design mode在设计模式下使用 ITemplate 的 Web 用户控件出错
【发布时间】:2011-10-13 15:23:34
【问题描述】:

我有一个带有以下标记的网络用户控件

<table>
    <tr>
        <td>
            <h1>
                <%= this.Title %></h1>
        </td>
    </tr>
    <tr>
        <td>
            <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        </td>
    </tr>
    <tr>
        <td>
            <h2>
                Footer</h2>
        </td>
    </tr>
</table>

后面的代码:

[ParseChildren(true, "Content"), PersistChildren(true)]
public partial class WebUserControl1 : System.Web.UI.UserControl
{
    public string Title { get; set; }

    [PersistenceMode(PersistenceMode.InnerDefaultProperty),
    TemplateContainer(typeof(ContentContainer)), 
    TemplateInstance(TemplateInstance.Single),
    DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]        
    public ITemplate Content { get; set; }

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

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        PlaceHolder1.Controls.Clear();
        var container = new ContentContainer();

        this.Content.InstantiateIn(container);
        PlaceHolder1.Controls.Add(container);
    }
}

public class ContentContainer : Control, INamingContainer
{
}

并在如下页面中使用

<%@ Register Src="WebUserControl1.ascx" TagName="WebUserControl1" TagPrefix="uc1" %>
<uc1:WebUserControl1 ID="WebUserControl11" runat="server" Title="The Title">
    <Content>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></Content>
</uc1:WebUserControl1>

当我运行该页面时,它执行得很好。当我在设计模式下查看页面时,出现以下错误:

类型“System.Web.UI.UserControl”没有名为的公共属性 “内容”。

我该如何解决这个问题?

编辑:我修改了代码

【问题讨论】:

    标签: asp.net user-controls webusercontrol itemplate


    【解决方案1】:

    您需要将 parse children 属性添加到您的用户控件类中,如下所示。

    ParseChildren(true, "Content")
    public partial class WebUserControl1 : System.Web.UI.UserControl
    

    这意味着在 ContentProvider 控件中,它的内部控件将是 解析并添加到其 Children 属性中。在设计时,它们将 作为其子控件持续存在。 详情请查看link

    【讨论】:

    • [ParseChildren(true, "Content"), PersistChildren(true)] 怎么样。您可能必须关闭页面并重新打开它才能解决任何缓存问题。你看过我链接的文章吗?它解决了这类设计师问题。
    • 另外,尝试将 Content 的持久化模式设置为 PersistenceMode(PersistenceMode.InnerDefaultProperty)
    • 我用我所做的更新了这个问题。不要担心重新打开页面,这是非常合乎逻辑的事情,即使在修改了代码之后,我也会重新构建项目并重新打开页面。
    • Content ITemplate 的持久化模式部分在您更新的代码中是错误的。我希望您尝试将其设置为 InnerDefaultProperty。
    【解决方案2】:

    来自 MSDN How to: Create Templated ASP.NET User Controls

    注意:Visual Studio 设计器不支持模板化的 ASP.NET 用户控件。但是,您可以在 Visual Studio 中编译和运行此示例。为此,当您创建 ASP.NET 页面来测试此代码时,请将页面中所有设计器生成的代码替换为示例清单中的代码和标记。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-27
      • 2015-02-13
      • 1970-01-01
      • 1970-01-01
      • 2010-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多