假设控件 X 有一个名为 RowTemplate
的模板.
所以 X 的标记应该是这样的:
<foo:X>
<RowTemplate>
<foo:Y>...</foo:Y>
</RowTemplate>
</foo:X>
我的问题是:Y 控件如何对数据上下文敏感?我知道我可以使用模板内联标签来访问数据上下文:<%# Eval("Id") %>
, 但我无法将此信息传递给 Y,因为服务器控件中不允许使用模板内联标记。
所以我不知道如何在 Y 中使用对象的 Id (Eval("Id"))。
最佳答案
通过向 ItemDataBound 事件(或 foo:X 控件上的其他类似事件)添加处理程序,您可以访问行模板中的控件。我的示例代码来自 DataList,因此您的事件处理程序可能会有所不同。
在后面的代码中 - 连接事件处理程序:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
foo.ItemDataBound += new DataListItemEventHandler(foo_ItemDataBound);
}
然后在事件处理程序中,访问您所在行中的控件。您的数据可能不是 DataRow,因此请根据需要进行更改。
void foo_ItemDataBound(object sender, DataListItemEventArgs e)
{
Control fooY = (e.Item.FindControl("foo:Y") as Control); //Replace foo:Y with the ID for foo:Y
DataRow data = e.Item.DataItem as DataRow;
fooY.SomeProperty = data["id"];
}
关于c# - 模板中的服务器控件如何对数据上下文敏感?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2136517/