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

时间:2011-08-01 17:32:04

标签: 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);
            }
        }

我在视图中的用法:

<%@ 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; }
...

3 个答案:

答案 0 :(得分:5)

解决方案--------------------------
我找到了一个非常好的解决方案,只需将[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; }
...

答案 1 :(得分:0)

我会用一种方法来访问用户控件中的内容控件:

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");

答案 2 :(得分:0)

当你在模板中编写一个控件时,你会给它一个内容如何的样本。想象一下,你在模板中给出一个网格的内容,其中一些id为“SomeTextBox”,当网格中的行数增加时,SomeTextBox不会多次出现。控件将在运行时动态命名。

但是你还有办法,你必须找到容器控件并申请, Control.FindControl()方法就可以了。 FindControl()获取您在模板设计时给出的模板控件ID。