Blazor中如何对布尔值取反?绑定取反值遇CS0131错误解决
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
Valueproperty to!Checkedso the checkbox starts off showing the inverted state of your originalCheckedvariable. - Two-way sync: When the checkbox is toggled, the
@onchangeevent triggers. We take the new value from the checkbox (changeArgs.Value), invert it, and assign it back toChecked. This keepsCheckedand 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

