以下代码经过简化。
用户控制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/