有人可以解释向中继器中的用户控件提供数据的最简单方法吗?
我有以下几点:
Default.aspx
<!-- 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();
}
CustomControl.ascx
<!-- 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
}
}
最佳答案
您可以将属性添加到用户控件,然后在数据绑定(bind)期间进行设置。
像这样:
<!-- 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
}
}
关于asp.net - 如何在转发器内的用户控件中提供 'data'?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6537143/