有人可以解释向转发器内的用户控件提供数据的最简单方法吗?
我有以下内容:
<!-- this.GetData() returns IEnumerable<Object> -->
<asp:Repeater runat="server" datasource='<%#this.GetData()%>'>
<ItemTemplate>
<my:CustomControl runat="server" datasource='<%#Container.DataItem %>
</ItemTemplate>
</asp:Repeater>
代码隐藏
protected void Page_Load(object sender, EventArgs e)
{
this.DataBind();
}
<!-- Object has property Title -->
<h1><%#this.DataSource.Title%></h1>
代码隐藏:
[System.ComponentModel.DefaultBindingProperty("DataSource")]
public partial class CustomControl : System.Web.UI.UserControl
{
public Item DataSource { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
var x = this.DataSource; //null here
}
protected void Page_PreRender(object sender, EventArgs e)
{
var x = this.DataSource; //still null
}
}
答案 0 :(得分:5)
您可以向用户控件添加属性,然后在数据绑定期间设置这些属性。
像这样:<!-- this.GetData() returns IEnumerable<Object> -->
<asp:Repeater runat="server" datasource='<%#this.GetData()%>'>
<ItemTemplate>
<my:CustomControl runat="server" title='<%#Container.DataItem.title %>
</ItemTemplate>
</asp:Repeater>
代码隐藏
protected void Page_Load(object sender, EventArgs e)
{
this.DataBind();
}
CustomControl.ascx
<!-- Object has property Title -->
<h1><%#this.Title%></h1>
代码隐藏:
[System.ComponentModel.DefaultBindingProperty("DataSource")]
public partial class CustomControl : System.Web.UI.UserControl
{
public Item DataSource { get; set; }
public string title { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
var x = this.DataSource; //null here
}
protected void Page_PreRender(object sender, EventArgs e)
{
var x = this.DataSource; //still null
}
}
答案 1 :(得分:-1)
我在这里的不同帖子上找到了一个优雅的解决方案: Anthony Pegram的ASP.NET Loading a User Control in a Repeater
要点:
使用转发器的ItemDataBound(对象发送器,RepeaterItemEventArgs e)事件将信息推送到Web用户控件的属性(您创建的)。