以下代码已经简化。
用户控件ascx:
这是我的用户控件代码后台:
用户控件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);
}
}
我在视图中的使用方法:
<%@ 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"控件,但好像它不存在(就像使用一个不存在的变量一样)。有什么想法吗?
提前感谢。
解决方案 --------------------------
我找到了一个非常好的解决方案,只需将用户控件的ITemplate属性添加 [TemplateInstance(TemplateInstance.Single)] ,就可以看到所有内容。现在我可以像正常页面控件一样使用它。
public partial class BaseFormControl : System.Web.UI.UserControl
{
[TemplateContainer(typeof(ContentContainer))]
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateInstance(TemplateInstance.Single)]
public ITemplate Content { get; set; }
...
TemplateInstance
。你的解决方案很好!+1 - Johnny5