ASP Repeater控件与多个模板
本文关键字:Repeater 控件 ASP | 更新日期: 2023-09-27 18:14:00
我怎么能有一个具有多个模板的重复器控件,其中选择的模板是基于项目的类型?
这是我目前拥有的:
我的中继器类:
[ToolboxData("<{0}:LifestreamRepeater runat=server>")]
public class LifestreamRepeater : Repeater
{
[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate TwitterTemplate {get; set;}
protected override void OnDataBinding(EventArgs e)
{
//base.OnDataBinding(e);
foreach (var item in (IEnumerable<LifestreamItem>)this.DataSource)
{
if (item is LifestreamTwitterItem)
{
LifestreamRepeaterItem ri = new LifestreamRepeaterItem(item);
TwitterTemplate.InstantiateIn(item);
}
else
{
ItemTemplate.InstantiateIn(item);
}
}
}
}
和前端:
<lfs:LifestreamRepeater runat="server" ID="repeater1">
<TwitterTemplate>
<div class="Lifestream Twitter Item">
<h4> <%# DataBinder.Eval(Container.DataItem, "Title")%> </h4>
<p> <%# DataBinder.Eval(Container.DataItem, "Body")%> </p>
</div>
</TwitterTemplate>
<ItemTemplate>
<div class="Lifestream Item">
<h2> <%# DataBinder.Eval(Container.DataItem, "Title")%> </h2>
<p> <%# DataBinder.Eval(Container.DataItem, "Body")%> </p>
</div>
</ItemTemplate>
</lfs:LifestreamRepeater>
然后我将中继器控件绑定到LifestreamItem的IEnumerable,这是多个不同社交网络帖子类型的基类,因此可能有TwitterLifestreamItem和VimeoLifestreamItem,我希望中继器选择不同的模板,具有不同的可能值,取决于数据项。
解决方案似乎是像这样重写DataBind方法:
public override void DataBind()
{
foreach (var item in (IEnumerable<LifestreamItem>)this.DataSource)
{
if (item is LifestreamTwitterItem)
{
TwitterTemplate.InstantiateIn(item); // instantiate inside the item which is also a control.
}
else
{
ItemTemplate.InstantiateIn(item);
}
item.DataBind(); // bind the item
Controls.Add(item); // add the item to the repeater
}
}
我不认为ASP中有什么内置的东西。但是你可以这样做:
<asp:Repeater ID="myRepeater" runat="server" OnItemDataBound="myRepeater_ItemDataBound">
<ItemTemplate>
<asp:PlaceHolder ID="twitterTemplate" Visible="false" runat="server">
<asp:Literal ID="fooTwitterControl" runat="server" />
</asp:PlaceHolder>
<asp:PlaceHolder ID="itemTemplate" Visible="false" runat="server">
<asp:Literal ID="fooItemControl" runat="server" />
</asp:PlaceHolder>
</ItemTemplate>
</asp:Repeater>
和ItemDataBound
事件:
protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (ListItemType.Item == e.Item.ItemType || ListItemType.AlternatingItem == e.Item.ItemType)
{
PlaceHolder twitterTemplate = (PlaceHolder)e.Item.FindControl("twitterTemplate");
PlaceHolder itemTemplate = (PlaceHolder)e.Item.FindControl("itemTemplate");
var item = (LifestreamItem)e.Item.DataItem;
if (item is LifestreamTwitterItem)
{
twitterTemplate.Visible = true;
Literal fooTwitterControl = (Literal)e.Item.FindControl("fooTwitterControl");
// Load all twitter related controls + populate
}
else
{
itemTemplate.Visible = true;
Literal fooItemControl = (Literal)e.Item.FindControl("fooItemControl");
// Load all non-twitter controls + populate
}
}
}
本质上,ItemTemplates
成为占位符,并根据您要迭代的类型启用/禁用