具有多个模板的ASP Repeater控件 [英] ASP Repeater control with multiple templates

查看:67
本文介绍了具有多个模板的ASP Repeater控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在具有多个模板的中继器控件中选择基于项目类型的模板?

How can I have a repeater control with multiple templates where the template chosen is based upon the type of the item?

这是我目前拥有的:

我的复读班:

[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,我希望转发器选择具有不同可能值的不同模板,具体取决于在数据项上.

Then I bind the repeater control to an IEnumerable of LifestreamItem which is a base class for multiple different social network post types so there might be TwitterLifestreamItem and VimeoLifestreamItem and I want the repeater to choose a different template, with different possible values, depending on the dataitem.

推荐答案

似乎解决方案是像这样重写DataBind方法:

It seems that the solution is to override the DataBind method like this:

    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 Repeater控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆