日期:2012-05-21  浏览次数:20393 次

为这个头痛了有一段时间了。尝试过一些方法也问了一些人查看了一些文档。终于功夫不负有心人,得出了一种比较简便清楚的方法。首先要实现ITemplate接口,建立了一个基类相关代码如下:Public Class BaseTemplate Implements ITemplate Protected TemplateType As ListItemType '模版的种类 Protected pnlMain As Panel '建立主面板 Sub New(ByVal type As ListItemType) Me.TemplateType = type End Sub Sub InstantiateIn(ByVal container As Control) Implements ITemplate.InstantiateIn Me.pnlMain = New Panel Select Case TemplateType Case ListItemType.Header AddHandler Me.pnlMain.DataBinding, AddressOf Me.HeaderTBinding Case ListItemType.Item AddHandler Me.pnlMain.DataBinding, AddressOf Me.ItemTBinding Case ListItemType.AlternatingItem AddHandler Me.pnlMain.DataBinding, AddressOf Me.AlternatingItemTBinding Case ListItemType.Footer AddHandler Me.pnlMain.DataBinding, AddressOf Me.FooterTBinding End Select container.Controls.Add(Me.pnlMain) End Sub '数据Item Protected Overridable Sub ItemTBinding(ByVal sender As Object, ByVal e As System.EventArgs) End Sub '头Item Protected Overridable Sub HeaderTBinding(ByVal sender As Object, ByVal e As System.EventArgs) End Sub '交替Item Protected Overridable Sub AlternatingItemTBinding(ByVal sender As Object, ByVal e As System.EventArgs) End Sub '脚Item Protected Overridable Sub FooterTBinding(ByVal sender As Object, ByVal e As System.EventArgs) End Sub End Class不是很晦涩。通过判断类型,为panel加载绑定事件。下面在给出一个实现的子类代码:Public Class MyTalkTemplate Inherits BaseTemplate Sub New(ByVal type As ListItemType) MyBase.New(type) End Sub Protected Overrides Sub ItemTBinding(ByVal sender As Object, ByVal e As System.EventArgs) Dim pnl As Panel Dim container As DataListItem pnl = CType(sender, Panel) container = CType(pnl.NamingContainer, DataListItem) Dim hTbl As New HtmlTable hTbl.Width = "100%" '保证足够宽 Dim hRow As HtmlTableRow Dim hCell As HtmlTableCell '图片 Dim img As New WebControls.Image img.Height = New Unit(80) '设定长和宽 img.Width = New Unit(80) img.ImageUrl = String.Format("{0}", container.DataItem("TalkImg")) hRow = New HtmlTableRow hCell = New HtmlTableCell hCell.RowSpan = 2 hCell.Controls.Add(img) hRow.Cells.Add(hCell) '主题 hCell = New HtmlTableCell hCell.Align = "Center" hCell.Controls.Add(New LiteralControl("<big>主题</big>")) hRow.Cells.Add(hCell) hTbl.Rows.Add(hRow) hRow = New HtmlTableRow hCell = New HtmlTableCell hCell.Width = "100%" '保证足够的宽度 hCell.VAlign = "Top" '竖直方向位于顶端 hCell.Controls.Add(New LiteralControl(String.Format("<h5>{0}</h5>", container.DataItem("TalkTitle")))) hRow.Cells.Add(hCell) hTbl.Rows.Add(hRow) '内容 hRow = New HtmlTableRow hCell = New HtmlTableCell hCell.ColSpan = 2 hCell.Height = "1" hCell.BgColor = "#808080" hRow.Cells.Add(hCell) hTbl.Rows.Add(hRow) hRow = New HtmlTableRow hCell = New HtmlTableCell hCell.ColSpan = 2 hCell.Controls.Add(New LiteralControl(String.Format("{0}", container.DataItem("TalkText")))) hRow.Cells.Add(hCell) hTbl.Rows.Add(hRow) Me.pnlMain.Controls.Add(hTbl) End Sub写的有点多余哈。就是利用container.DataItem来建立各个控件。之所以不直接在实现接口时间直接利用绑定的信息来建立控件,是因为事件顺序。InstantiateIn