访问Repeater中的控件

时间:2012-01-20 16:14:26

标签: c# asp.net user-controls sitecore

假设我有以下内容:

<asp:Repeater ID="repSubItems" runat="server" DataSource="<%# SubItems %>" >
    <ItemTemplate>
        <sc:FieldRenderer ID="FieldRenderer1" 
            FieldName="BlurbSpot_Content_SubHeading" 
            runat="server" 
            Item="<%# Container.DataItem as Sitecore.Data.Items.Item %>" />  
    </ItemTemplate>
</asp:Repeater>

我想在代码背后能够做到:

FieldRenderer1.Style["Width"] = MyCoolWidth;

但在Repeater内,我无法访问FieldRenderer1控件。

2 个答案:

答案 0 :(得分:6)

您需要处理ItemDataBound转发器的repSubItems事件。例如:

protected void repSubItems_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        var fieldRenderer1 = e.Item.FindControl("FieldRenderer1") as Sitecore.Web.UI.WebControls.FieldRenderer;
        if (fieldRenderer1 != null)
        {
            fieldRenderer1.Style["Width"] = MyCoolWidth;
        }

    }
}

答案 1 :(得分:1)

您需要在Repeater中找到您正在寻找的行,然后找到该控件。以下示例可以为Repeater中的所有项目执行此操作:

// repeater item
foreach (Control cr in repSubItems.Controls)
{
    // assuming this is your templated control name and not the final output name
    FieldRenderer founcControl = cr.FindControl("FieldRenderer1") as FieldRenderer;

    founcControl .Style["Width"] = MyCoolWidth;
}

执行此操作的更好的方式将是专门为您的控件实现OnDataBinding,因为那时您无法进行搜索:

<sc:FieldRenderer ID="FieldRenderer1" FieldName="BlurbSpot_Content_SubHeading"
    runat="server" Item="<%# Container.DataItem as Sitecore.Data.Items.Item %>"
     OnDataBinding="FieldRenderer1_DataBinding" />

protected void FieldRenderer1_DataBinding(object sender, System.EventArgs e)
{
    FieldRenderer rend = (FieldRenderer)(sender);

    // you can do whatever you want to rend at this point and it is scoped to ONLY
    // the control so you never have to search for it.
    rend.Style["Width"] = MyCoolWidth;  
}