在codebehind数据绑定列表为用户控件中的一个项目模板 [英] Databinding a List to a usercontrol in an Item Template in codebehind
问题描述
我有一个DataList象下面这样:
I have a DataList like below:
<asp:DataList runat="server" ID="myDataList">
<ItemTemplate>
<uc:MyControl ID="id1" runat="server" PublicProperty='<%# Container.DataItem %>' />
</ItemTemplate>
</asp:DataList>
项模板是一个简单的注册用户控件,MyControl。为DataList的数据源是一个列表&LT;名单&LT; T&GT;&GT;
和MyControl的PublicProperty传递列表&LT; T&GT;
它然后peforms自身的数据绑定。这工作得很好,但我必须在ASPX / C页面数据绑定一般厌恶。什么是设置在后面的code中的PublicProperty价值的最efficent方法是什么?
The Item Template is simply a registered usercontrol, MyControl. The DataSource for the DataList is a List<List<T>>
and MyControl's PublicProperty is passed List<T>
which it then peforms its own databinding on. This works fine, but I have a general aversion to databinding in the aspx/c page. What is the most efficent way to set the PublicProperty value in the code behind?
推荐答案
如果在在线数据绑定语法是不是你不够好 - 你总是可以挂接到DataList控件的ItemDataBound事件
If in line data binding syntax is not good enough for you - you can always hook into the ItemDatabound event of the DataList.
<asp:DataList runat="server" ID="myDataList"
OnItemDataBound="DataList_ItemDataBound">
<ItemTemplate>
<uc:MyControl ID="id1" runat="server" />
</ItemTemplate>
</asp:DataList>
然后,在你的页面背后的code /包含控制你可以添加你ItemDataBound事件。
Then, in the code behind of your page/containing control you can add your ItemDataBound event.
protected void DataList_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item
|| e.Item.ItemType == ListItemType.AlternatingItem)
{
DataListItem item = e.Item;
//List<string> or whatever your data source really is...
List<string> dataItem = item.DataItem as List<string>;
MyControl lit = (MyControl)item.FindControl("id1");
lit.PropertyName = dataItem;
}
}
有关的DataList.ItemDataBound事件的详细信息 - 的阅读这里
For more information on the DataList.ItemDataBound event - Read Here
如果您不想在ASPX声明你的ItemDataBound委托直列你也可以做到这一点在后面的code - 也许在你的页面加载事件:
If you would rather not declare your ItemDataBound delegate inline in the ASPX you could also do it in the code behind - probably in your Page Load event:
myDataList.ItemDataBound += DataList_ItemDataBound;
希望帮助
这篇关于在codebehind数据绑定列表为用户控件中的一个项目模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!