如何在Blazor WebAssembly中禁用InputRadioGroup?
在Blazor WebAssembly中禁用InputRadioGroup的解决方法
Blazor官方的InputRadioGroup组件本身并没有暴露Disabled参数,所以直接添加Disabled="true"不会生效。以下是几种可行的解决办法:
方法一:统一控制组内所有InputRadio的禁用状态
InputRadio组件支持Disabled参数,你可以将一个布尔变量绑定到组内每个InputRadio的Disabled属性,实现一键禁用整个单选组:
@code { // 控制禁用状态的变量 private bool IsRadioGroupDisabled = true; private string SelectedOption { get; set; } } <InputRadioGroup @bind-Value="SelectedOption"> <InputRadio Value="OptionA" Disabled="IsRadioGroupDisabled" /> 选项A <InputRadio Value="OptionB" Disabled="IsRadioGroupDisabled" /> 选项B <InputRadio Value="OptionC" Disabled="IsRadioGroupDisabled" /> 选项C </InputRadioGroup> <!-- 可添加按钮测试状态切换 --> <button @onclick="() => IsRadioGroupDisabled = !IsRadioGroupDisabled"> @(IsRadioGroupDisabled ? "启用单选组" : "禁用单选组") </button>
这种方法简单直接,无需自定义组件,适合大多数常规场景。
方法二:自定义封装支持Disabled的InputRadioGroup
如果需要在多个页面复用禁用逻辑,可以自定义组件封装该功能:
自定义InputRadioGroup组件
@inherits InputRadioGroup<string> <!-- 通过级联值将禁用状态传递给子InputRadio --> <CascadingValue Name="RadioGroupDisabled" Value="Disabled"> @ChildContent </CascadingValue> @code { [Parameter] public bool Disabled { get; set; } }
自定义InputRadio组件
@inherits InputRadio<string> <input type="radio" id="@Id" class="@CssClass" value="@Value" disabled="@Disabled" @onchange="HandleChange" /> <label for="@Id">@ChildContent</label> @code { // 接收来自父组的级联禁用状态 [CascadingParameter(Name = "RadioGroupDisabled")] public bool Disabled { get; set; } private void HandleChange(ChangeEventArgs e) { // 禁用状态下不处理选择事件 if (!Disabled) { CurrentValueAsString = e.Value.ToString(); } } }
使用自定义组件
@code { private bool IsDisabled = true; private string SelectedOption { get; set; } } <CustomInputRadioGroup @bind-Value="SelectedOption" Disabled="IsDisabled"> <CustomInputRadio Value="OptionA" /> 选项A <CustomInputRadio Value="OptionB" /> 选项B </CustomInputRadioGroup>
方法三:CSS+交互禁用(仅前端视觉/交互层面)
如果只是需要快速实现视觉上的禁用,且不担心用户通过DOM修改绕过,可以用CSS禁用交互:
@code { private bool IsDisabled = true; private string SelectedOption { get; set; } } <InputRadioGroup @bind-Value="SelectedOption" class="@(IsDisabled ? "radio-group-disabled" : "")"> <InputRadio Value="OptionA" /> 选项A <InputRadio Value="OptionB" /> 选项B </InputRadioGroup> <style> .radio-group-disabled input[type="radio"] { pointer-events: none; opacity: 0.6; cursor: not-allowed; } .radio-group-disabled label { cursor: not-allowed; } </style>
注意:这种方法仅阻止用户交互,实际DOM中的单选框并未真正设置disabled属性,表单提交时仍可能被篡改,仅适合非敏感场景。
内容的提问来源于stack exchange,提问作者mko
相关产品推荐
相关产品推荐

