我有一个表示嵌套层次结构的类(MyClass),所以该类有一个属性,它是MyClass的集合。 MyClass也有一个标题属性动态添加用户控件到中继器
为了在网页上显示它,我希望创建一个有中继器的用户控件。在项目模板中,我将使用文字显示标题属性,并在中继器的ItemCreated事件上创建一个新的usercontrol实例,并将其添加到中继器中的当前项目中。
我的问题是,当usercontrol中的Page_Load事件触发时,如果控件是动态添加的,即使我调用EnsureChildControls,repMyClass repeater poroperty也为null。我在这里错过了什么吗?如果我创建一个中继器并将我的userctonrol放在项目模板中,它可以正常工作。我不能让这个动态工作?
用户控制:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MyControl.ascx.cs" Inherits="MyControl" %>
Items:<br/>
<asp:Repeater ID="repMyClass" runat="server" EnableViewState="false"
OnItemCreated="repMenuItems_ItemCreated">
<HeaderTemplate><ul><HeaderTemplate>
<ItemTemplate>
<li><%# Eval("Title") %>
<div><asp:PlaceHolder ID="SubItemPlaceholder" runat="server" /></div>
</li></ItemTemplate>
<FooterTemplate></ul></FooterTemplate>
</asp:Repeater>
用户控制代码:
public partial class MyControl: System.Web.UI.UserControl
{
public IEnumerable<MyClass> ChildItems { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
this.repMyClass.DataSource = ChildItems;
this.repMyClass.DataBind();
}
protected void repMenuItems_ItemCreated(object Sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
//Get the MyClass instance for this repeater item
MyClass mcCurrent = (MyClass)e.Item.DataItem;
//If the MyClass instance has child instances
if (mcCurrent.Children != null && mcCurrent.Children.Length > 0)
{
//Add a new user control and set it's property so it can bind
PlaceHolder ph = (PlaceHolder)e.Item.FindControl("SubItemPlaceholder");
MyControl ctl = (MyControl)Page.LoadControl(typeof(MyControl),new object[] {});
ctl.ChildItems = mcCurrent.Children;
ph.Controls.Add(ctl);
}
}
}
}
你可以编辑这个来解释,也许清理这个。我想也许你在这句话中有一半编辑没有完成? “我的问题是,当Page_Load事件首先用于动态添加的控件时,repNyClass repeater poroperty为null” – chrismay