代码之家  ›  专栏  ›  技术社区  ›  Andre Pena

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

  •  3
  • Andre Pena  · 技术社区  · 15 年前

    假设控件x有一个名为 RowTemplate .

    所以X的标记应该是:

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

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

    所以我不知道如何在y中使用对象的id(eval(“id”)。

    1 回复  |  直到 15 年前
        1
  •  1
  •   s_hewitt    15 年前

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

    在代码隐藏-连接事件处理程序中:

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
    
        foo.ItemDataBound += new DataListItemEventHandler(foo_ItemDataBound);
    }
    

    然后在事件处理程序中,访问行中的控件。您的数据可能不是数据行,因此请根据需要进行更改。

    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"];
    }