访问中继器中的控件
本文关键字:控件 中继器 访问 | 更新日期: 2023-09-27 18:20:51
假设我有以下内容:
<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
控制。
您需要处理repSubItems
中继器的ItemDataBound
事件。示例:
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;
}
}
}
您需要在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;
}