[英]Accessing child controls that are in a templated user control ASP.NET
以下代碼已簡化。
用戶控件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”控件,但它就像它不存在(比如使用不存在的變量)。 有任何想法嗎?
提前致謝。
解決方案--------------------------
我找到了一個非常好的解決方案,只需將[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; }
...
我會用一種方法來訪問用戶控件中的內容控件:
public Control FindInnerControl (string id)
{
if (contentHolder.Controls.Count > 0)
{
return contentHolder.Controls [0].FindControl (id); //The first control is your ContentContainer
}
return null;
}
然后在你的頁面背后的代碼中你可以做
TextBox txtKeytbcss = (TextBox) BaseFormControl1.FindInnerControl ("keytbcss");
當您在模板中編寫控件時,您將給它一個內容如何的樣本。 想象一下,你在模板中給出一個網格的內容,其中一些id為“SomeTextBox”,當網格中的行數增加時,SomeTextBox不會多次出現。 控件將在運行時動態命名。
但是你還有辦法,你必須找到容器控件並在其上應用Control.FindControl()方法。 FindControl()獲取您在設計時提供的模板控件ID。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.