【ASP.net】解析Repeater 控件的模板

来源:互联网 发布:h3c 绑定mac地址 编辑:程序博客网 时间:2024/05/21 10:26

1.Repeater控件

    顾名思义,repeat有重复的意思。解释就是用于显示重复的项目列表,这些项目被限制在该控件。 Repeater控件不具备内置的呈现功能,用户必须通过创建模板来为它提供布局.

    重复的东西就说明有很多相同的,那就可以抽出来。抽出来的东西,面向对象中叫类,设计模式中可以是模板方法。在Repeater控件这里呢,就叫模板了。

    这篇博客主要总结一下repeater控件的5种模板的使用及效果显示。


2.  五种模板:


1> ItemTemplate:

    对每一个数据项进行格式设置。

    假设Repeater是一个表格,则它就有多个行组成,而每一行显示的数据,就是有ItemTemplate控制的.这里的数据绑定也可通过DataSource属性来绑定.


例:

       <span style="font-family:KaiTi_GB2312;font-size:18px;">  <ItemTemplate>                <font color="Red" Size="20"> //字体颜色红色,大小20                    <%#DataBinder.Eval(Container.DataItem,"userName") %>                    <%#DataBinder.Eval(Container.DataItem,"userPwd") %>                   <br> //换行                </font>          </ItemTemplate></span>
结果:     

                  

     在上述数据绑定的时候用到了DataBinder.Eval,大家可以了解一下Eval与DataBinder.Eval的不同之处。


2> AlternatingItemTemplate :

     对每一个交替数据项进行设置.

     如果你在代码中同时设置了Itemplate和AlternatingItemTemplate,则数据第一行会按照itemTemplate中的设置显示,第二行会按照AlternatingitemTemplate中的设置显示,如此交替显示所绑定的数据. 

     这里的数据绑定和上述模板中的数据绑定一样.如果在代码中只设置了上述模板中的一个属性,则数据就会按照所选择模板的设置显示。

 代码:

               <ItemTemplate>                   <font color="Red" Size="20">         <%--字体颜色红色,大小20--%>                              <%#DataBinder.Eval(Container.DataItem,"userName") %>                     <%#DataBinder.Eval(Container.DataItem,"userPwd") %>                     <br>                           <%--//换行--%>                       </font>                 </ItemTemplate>              <strong> </strong> <alternatingitemTemplate>                     <font color="blue">                         <%#DataBinder.Eval(Container.DataItem,"userName") %>                         <%#DataBinder.Eval(Container.DataItem,"userPwd") %>                     <br></font>               </alternatingitemTemplate>
结果:

               

3> SeparatorTemplate:

    对分隔符进行设置.此模板中不能进行数据绑定.

    如下例子中添加了一条蓝色直线.

代码:

            <SeparatorTemplate>                     <hr color="blue" size="2">             </SeparatorTemplate>
结果:

                

4> HeaderTemplate和FooterTemplate

    对页眉和页脚进行设置. 这里需要注意的就是:页眉页脚模板里,不能进行数据绑定.

代码:
         <span style="font-family:KaiTi_GB2312;font-size:18px;">     <HeaderTemplate>                   <h3>模板页眉</h3>            </HeaderTemplate>            <FooterTemplate>                   <h3>模板页脚</h3>            </FooterTemplate></span>

结果:    
 
           

总结:

    前两个模板可进行数据绑定,后三个模板不能进行数据绑定.Itemplate模板是必须的,其余的模板可以根据需求选择是否要添加. 

  

   

1 0