(转)动态创建 ListView 模板

想必大家已经喜欢上了ListView的布局方式,在LayoutTemplate中定义展现方式,在其它模板中定义数据绑定,使得我们设计数据表现页更简单了。
不过我最近在想一个问题,如果listview中要显示的列并非固定的,或者我们要在其中实现列的重新排列该怎么办呢?本篇文章将要讲述如何动态的为listview创建模板。
首先是第一种简单方式 this.ListView1.LayoutTemplate = this.LoadTemplate("MyTemplate.ascx");这是最简单的一种方式,但是相对的灵活性也不足,他只能是为我们的listview提供可预知的集中模板。并不能在用户操作的时候实现改变。那么该怎么办呢?
若要创建动态模板,就要先创建模板类,然后在需要时实例化该类。

创建实现ITemplate接口的新类,并实现接口的InstantiateIn方法。
    该方法提供将文本实例或控件实例插入容器的方法。
    我们以LayoutTemplate为例

public class MyLayoutTemplate : System.Web.UI.ITemplate
{
public void InstantiateIn(System.Web.UI.Control container)
{
            PlaceHolder ph = new PlaceHolder();
            Table t = new Table();
            TableRow r = new TableRow();

            r.Cells.Add(new TableCell() { Text = "Title1" });
            r.Cells.Add(new TableCell() { Text = "Title2" });
            r.Cells.Add(new TableCell() { Text = "Title3" });
            t.Rows.Add(r);
            TableRow itemPlaceholderRow = new TableRow();

            Table itemPlaceholderTable = new Table();
            itemPlaceholderTable.ID = "itemPlaceholder";
            itemPlaceholderRow.Cells.Add(new TableCell());
            itemPlaceholderRow.Cells[0].Controls.Add(itemPlaceholderTable);

            t.Rows.Add(itemPlaceholderRow);
            ph.Controls.Add(t);
            container.Controls.Add(ph);
        }
    }

然后我们只需要创建这个类的实例并将其赋给LayoutTemplate属性就OK了。

            MyLayoutTemplate myLayoutTemplate = new MyLayoutTemplate();

this.ListView1.LayoutTemplate = myLayoutTemplate;

下面我们创建ItemTemplate,在这里我们还要额外多处理下DataBinding事件。
结果代码如下

public class MyItemTemplate : System.Web.UI.ITemplate
{
public void InstantiateIn(System.Web.UI.Control container)
{
            PlaceHolder ph = new PlaceHolder();
            TableRow row = new TableRow();
            row.Cells.Add(new TableCell() { ID = "cell1" });
            row.Cells.Add(new TableCell() { ID = "cell2" });
            ph.Controls.Add(row);
            ph.DataBinding += new EventHandler(ph_DataBinding);
            container.Controls.Add(ph);
        }

void ph_DataBinding(object sender, EventArgs e)
{
            PlaceHolder ph = (PlaceHolder)sender;
            IDataItemContainer ri = (IDataItemContainer)ph.NamingContainer;
object itemValue1 = DataBinder.Eval(ri.DataItem, "字段1");
            ((TableCell)ph.FindControl("cell1")).Text = itemValue1.ToString();
object itemValue2 = DataBinder.Eval(ri.DataItem, "字段2");
            ((TableCell)ph.FindControl("cell2")).Text = itemValue2.ToString();
        }
    }

同样的,使用this.ListView1.ItemTemplate = new MyItemTemplate();完成ItemTemplate的编辑。
如果你愿意多花点时间,您肯定可以举一反三的搞定其它类型的模板。

(来源:http://www.cnblogs.com/tianyamoon/archive/2008/05/07/1187307.html)

posted @ 2011-03-25 17:51  芳草萋萋  阅读(352)  评论(0编辑  收藏  举报