如何在运行时向ItemTemplate(Repeater)添加控件?

时间:2023-01-27 13:37:01

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?

我正在设计一个丰富的转发器控件,它需要在运行时添加一些控件(特别是一个无序列表)。我选择的解决方案是将nesseccary标记onInit分别注入标题,项目和页脚模板。我可以取出模板(使用InstantiateIn)然后根据需要添加标记,但我不知道将模板添加回转发器的方法?

1 个解决方案

#1


4  

In the past I've simply handled the ItemDataBound Event and modified the current RepeaterItem with whatever I needed to do.

在过去,我只是简单地处理了ItemDataBound事件并使用我需要做的任何事情修改了当前的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>");
    }
}

#1


4  

In the past I've simply handled the ItemDataBound Event and modified the current RepeaterItem with whatever I needed to do.

在过去,我只是简单地处理了ItemDataBound事件并使用我需要做的任何事情修改了当前的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>");
    }
}