创建实现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