模板中的服务器控件如何对数据上下文敏感?

时间:2021-09-23 06:23:08

Let's say a control X has a template called RowTemplate.

假设一个控件X有一个名为RowTemplate的模板。

So X's markup would be like:

所以X的标记就像:

<foo:X>
    <RowTemplate>
        <foo:Y>...</foo:Y>
    </RowTemplate>
</foo:X>

My question is: How can the Y control be sensitive to the data context? I know I can use template inline tags to get access to the data context: <%# Eval("Id") %>, but I cannot pass this information to Y because template inline tags are not allowed in server controls.

我的问题是:Y控件如何对数据上下文敏感?我知道我可以使用模板内联标签来访问数据上下文:<%#Eval(“Id”)%>,但我无法将此信息传递给Y,因为服务器控件中不允许使用模板内联标记。

So I don't know how I could use the Object's Id (Eval("Id")) in Y.

所以我不知道如何在Y中使用Object的Id(Eval(“Id”))。

1 个解决方案

#1


1  

By adding a handler to the ItemDataBound event (or some other similar event on your foo:X control), you can access controls in your row template. My example code is from a DataList, so your event handlers will probably be different.

通过向ItemDataBound事件(或foo:X控件上的其他类似事件)添加处理程序,您可以访问行模板中的控件。我的示例代码来自DataList,因此您的事件处理程序可能会有所不同。

In the code behind - wire up the event handler:

在后面的代码中 - 连接事件处理程序:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);

    foo.ItemDataBound += new DataListItemEventHandler(foo_ItemDataBound);
}

Then in the event handler, access the controls in your row. Your data might not be a DataRow, so change that as needed.

然后在事件处理程序中,访问行中的控件。您的数据可能不是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"];
}

#1


1  

By adding a handler to the ItemDataBound event (or some other similar event on your foo:X control), you can access controls in your row template. My example code is from a DataList, so your event handlers will probably be different.

通过向ItemDataBound事件(或foo:X控件上的其他类似事件)添加处理程序,您可以访问行模板中的控件。我的示例代码来自DataList,因此您的事件处理程序可能会有所不同。

In the code behind - wire up the event handler:

在后面的代码中 - 连接事件处理程序:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);

    foo.ItemDataBound += new DataListItemEventHandler(foo_ItemDataBound);
}

Then in the event handler, access the controls in your row. Your data might not be a DataRow, so change that as needed.

然后在事件处理程序中,访问行中的控件。您的数据可能不是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"];
}