c# - 访问模板化用户控件 ASP.NET 中的子控件

标签 c# asp.net templates user-controls

以下代码经过简化。

用户控制ascx:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="BaseFormControl.ascx.cs"
    Inherits="SOPR.CustomForms.BaseFormControl" %>
<fieldset class="fset1">
</fieldset>

这是我的用户控制代码隐藏:

public partial class BaseFormControl : System.Web.UI.UserControl
    {



        [TemplateContainer(typeof(ContentContainer))]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public ITemplate Content { get; set; }



   void Page_Init()
        {




            if (Content != null)
            {
                ContentContainer cc = new ContentContainer();
                Content.InstantiateIn(cc);
                contentHolder.Controls.Add(cc);
            }
        }

我在 View 中的用法:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AddOperator.aspx.cs"
    Inherits="SOPR.Cadastro.AddOperator" MasterPageFile="~/MasterPage.Master" %>

<asp:Content ContentPlaceHolderID="ContentPlaceHolder1" ID="maincont" runat="server"     EnableViewState="true">
    <uc:BaseFormControl ID="BaseFormControl1" runat="server">
        <Content>
      <asp:TextBox runat="server" CssClass="keytbcss" MaxLength="4" ID="keytb"
                NewLine="false" />
        </Content>
    </uc:BaseFormControl>

我正在尝试访问代码隐藏上的“keytb”控件,但它就像不存在一样(就像使用不存在的变量一样)。有什么想法吗?

提前致谢。

解决方案------------------------
我找到了一个非常好的解决方案,只需将 [TemplateInstance(TemplateInstance.Single)] 添加到用户控件的 ITemplate 属性中,一切都会被看到。我现在可以像使用普通页面控件一样使用它。

public partial class BaseFormControl : System.Web.UI.UserControl
{



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

最佳答案

解决方案------------------------
我找到了一个非常好的解决方案,只需将 [TemplateInstance(TemplateInstance.Single)] 添加到用户控件的 ITemplate 属性中,一切都会被看到。我现在可以像使用普通页面控件一样使用它。

public partial class BaseFormControl : System.Web.UI.UserControl
{



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

关于c# - 访问模板化用户控件 ASP.NET 中的子控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6902133/

相关文章:

c++ - 在未调用的转换函数上在模板中编译错误

c++ - 专用于 const char * 的模板也会接受 char * 吗?

C# 加载整数并显示奇数/偶数

javascript - ASP.NET CompositeScript 路径结果为 404

c# - Automapper 继承的源和目标

asp.net - 将 Twitter Bootstrap 与 Asp.net MVC 3 表单集成

asp.net - 使用 BotDetect 验证码时为 "Object reference not set to an instance of an object."

c++ - 将任何函数作为模板参数传递?

c# - 如何检查应用程序是否有权访问目录?

c# - 同时保存两个 .xlsm 文件(每个大约 7MB)时,ClosedXML .SaveAs(MemoryStream ms) 没有进展