将控件 属性 绑定到表达式
Binding a control property to an expression
使用 ASP.NET WebForms,是否可以将控件的 属性 绑定到表达式?
例如
Visible="<% myProp.Value == otherProp.Value %>"
我知道我可以在代码隐藏中执行此操作,但我正在尝试将 UI 显示细节尽可能限制在标记中。
是的,这是进行 ASP.Net WebForms 开发的最有效方法。
您想调用 DataBind()
来计算 <%# myProp.Value == otherProp.Value %>
表达式。我更喜欢在 Page_PreRender
中调用 DataBind()
示例:
protected void Page_PreRender(object sender, EventArgs e)
{
DataBind();
}
<asp:PlaceHolder runat="server" Visible='<%# myProp.Value == otherProp.Value %>'>
Hello
</asp:PlaceHolder>
事实上,您可以将数据绑定逻辑放在页面的基础 class 中,或者放在 <script runat="server">
块中。
完整页面示例:
<%@ Page Language="C#" %>
<script runat="server">
void Page_PreRender(object sender, EventArgs e)
{
DataBind();
}
</script>
<html>
<body>
<asp:Placeholder runat="server" Visible='<%# DateTime.Now.Seconds % 2 == 1 %>'>
It is now an odd second
</asp:Placeholder>
</body>
</html>
使用 ASP.NET WebForms,是否可以将控件的 属性 绑定到表达式?
例如
Visible="<% myProp.Value == otherProp.Value %>"
我知道我可以在代码隐藏中执行此操作,但我正在尝试将 UI 显示细节尽可能限制在标记中。
是的,这是进行 ASP.Net WebForms 开发的最有效方法。
您想调用 DataBind()
来计算 <%# myProp.Value == otherProp.Value %>
表达式。我更喜欢在 Page_PreRender
DataBind()
示例:
protected void Page_PreRender(object sender, EventArgs e)
{
DataBind();
}
<asp:PlaceHolder runat="server" Visible='<%# myProp.Value == otherProp.Value %>'>
Hello
</asp:PlaceHolder>
事实上,您可以将数据绑定逻辑放在页面的基础 class 中,或者放在 <script runat="server">
块中。
完整页面示例:
<%@ Page Language="C#" %>
<script runat="server">
void Page_PreRender(object sender, EventArgs e)
{
DataBind();
}
</script>
<html>
<body>
<asp:Placeholder runat="server" Visible='<%# DateTime.Now.Seconds % 2 == 1 %>'>
It is now an odd second
</asp:Placeholder>
</body>
</html>