C# 如何在运行时向 ItemTemplate (Repeater) 添加控件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/271637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add controls to ItemTemplate (Repeater) at run time?
提问by Adam Naylor
I'm desinging a rich repeater control which needs some controls (specifically just an unordered list) added to it at runtime.
The solution I've opted for is to inject the nesseccary markup, onInit, into the header, item and footer templates respectively.
I can get the templates out (using InstantiateIn) and then add the markup as needed, but I don't know a way to add the template back in to the repeater?
我正在设计一个丰富的转发器控件,它需要在运行时添加一些控件(特别是一个无序列表)。
我选择的解决方案是将必要的标记 onInit 分别注入页眉、项目和页脚模板。
我可以取出模板(使用 InstantiateIn),然后根据需要添加标记,但我不知道如何将模板添加回中继器?
回答by Adrian Clark
In the past I've simply handled the ItemDataBound Event
and modified the current RepeaterItem
with whatever I needed to do.
在过去,我只是简单地处理ItemDataBound Event
并修改了当前RepeaterItem
需要做的任何事情。
Example:
例子:
private void Repeater1_ItemDataBound(object Sender, RepeaterItemEventArgs e)
{
// Make sure you filter for the item you are after
if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
{
PlaceHolder listLocation = (PlaceHolder)e.Item.FindControl("listPlaceHolder");
var subItems = ((MyClass)e.Item.DataItem).SubItems;
listLocation.Controls.Add(new LiteralControl("<ul>");
foreach(var item in subItems)
{
listLocation.Controls.Add(new LiteralControl("<li>" + item + "</li>"));
}
listLocation.Controls.Add(new LiteralControl("</ul>");
}
}