异常 "The name 'BindItem' does not exist in the current context"

Exception "The name 'BindItem' does not exist in the current context"

我最近发现您可以在 GridView 或 DetailsView 等数据绑定控件上下文中的 aspx 页面标记中直接使用 "BindItem" 和 "Item"(通过指定 ItemType 属性)。我现在想要实现的是成员的内联比较,例如:

    <asp:RadioButton Text="All Assigned" ID="rb1" 
         Checked='<%# BindItem.AllAssigned %>' 
         runat="server" GroupName="AllAssigned" />
    <asp:RadioButton Text="Responsible only"  ID="rb2" 
         Checked='<%# !BindItem.AllAssigned %>' 
         runat="server" GroupName="AllAssigned" />

在这种情况下,我需要双向绑定,所以我选择了 BindItem 表达式。 但似乎像 !BindItem.AllAssignedBindItem.AllAssigned == false 这样的表达式在标记中不起作用。他们给了我

这样的例外

名称'BindItem'在当前上下文中不存在

DataBinding:DataContext.MyEntity 不包含名称为 'false' 的 属性。

对于这样的表达式我要写什么?

由于您不能在数据绑定表达式中使用逻辑否定运算符,您可以在数据绑定表达式中使用 Eval()DataBinder.Eval() 来使用它,如下例所示:

<%-- alternative 1 --%>
<asp:RadioButton Text="Responsible only"  ID="rb2" 
         Checked='<%# !(bool)Eval("AllAssigned") %>' 
         runat="server" GroupName="AllAssigned" />

<%-- alternative 2 --%>
<asp:RadioButton Text="Responsible only"  ID="rb2" 
         Checked='<%# !Convert.ToBoolean(Eval("AllAssigned")) %>' 
         runat="server" GroupName="AllAssigned" />

如果您想启用双向绑定,而不是使用具有不同 ID 的单独单选按钮,请使用 RadioButtonList 并在 SelectedValue 属性 中设置 Bind(),如下所示下面的示例:

<asp:RadioButtonList ID="rb" runat="server" SelectedValue='<%# Bind("AllAssigned") %>' RepeatDirection="Horizontal" ...>
    <asp:ListItem Text="All Assigned" Value="true"></asp:ListItem>
    <asp:ListItem Text="Responsible only" Value="false"></asp:ListItem>
</asp:RadioButtonList>

然后您可以使用 rb.SelectedValue 检索选定的单选按钮值。

相关问题:Databinding of RadioButtonList using SelectedValue...possible?