You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor中如何对布尔值取反?绑定取反值遇CS0131错误解决

Fixing CS0131 When Binding Inverted Boolean to MatCheckbox

The error you're seeing (CS0131) makes total sense—@bind-Value needs a target that can be assigned a value (like a variable, property, or indexer), and !Checked is just a read-only expression, not something you can set directly.

The good news is you can achieve the inverted two-way binding without creating extra properties by manually unpacking what @bind-Value does under the hood. Here's the working code:

<MatCheckbox 
    Value="@(!Checked)" 
    @onchange="(changeArgs) => Checked = !changeArgs.Value" 
    Label="Checkbox"
></MatCheckbox>

How this works:

  • Initial state: We set the Value property to !Checked so the checkbox starts off showing the inverted state of your original Checked variable.
  • Two-way sync: When the checkbox is toggled, the @onchange event triggers. We take the new value from the checkbox (changeArgs.Value), invert it, and assign it back to Checked. This keeps Checked and the checkbox's visible state in sync (with the inversion you want).

This approach skips the @bind-Value syntactic sugar and uses Blazor's core binding mechanics directly—no extra properties required. If you ever need this pattern repeatedly, a custom component could clean things up, but for one-off use, this is perfect.

内容的提问来源于stack exchange,提问作者Vencovsky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 20:57:35