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

MudBlazor Table中无选中行时如何正确禁用按钮

MudTable 未选中行时禁用按钮的正确实现

你之前写的Disabled=(selectedRow is null)逻辑本身没有问题,不生效通常是两个原因:一是没有给MudTable正确配置选中项的双向绑定,导致自定义的selectedRow变量拿不到组件内部的选中状态;二是开启了多选模式,却用单个行对象是否为空做判断。
分两种常见场景实现即可:

单选模式实现

单选模式需要给MudTable绑定@bind-SelectedItem到你的选中行字段,同时开启行选中触发能力,按钮的禁用判断直接判断该字段是否为null即可。

@* 表格组件 *@
<MudTable T="DataItem" 
          @bind-SelectedItem="selectedRow" 
          Hover="true" 
          SelectOnRowClick="true">
    <HeaderContent>
        <MudTh>ID</MudTh>
        <MudTh>名称</MudTh>
    </HeaderContent>
    <RowTemplate>
        <MudTd>@context.Id</MudTd>
        <MudTd>@context.Name</MudTd>
    </RowTemplate>
</MudTable>

@* 操作按钮 *@
<MudButton Disabled="@(selectedRow is null)" 
           Variant="Variant.Filled" 
           Color="Color.Primary">
    编辑选中行
</MudButton>

@code {
    // 绑定的选中行字段
    private DataItem? selectedRow;
    // 其余表格数据、业务逻辑
}

注意:必须配置SelectOnRowClick="true",或者在列模板中添加选中复选框,否则点击行不会触发选中状态更新。

多选模式实现

多选模式需要开启MultiSelection="true",同时绑定@bind-SelectedItems到集合类型的字段,按钮禁用判断要改成判断选中集合是否为空,不能判断单个对象是否为null。

@* 表格组件 *@
<MudTable T="DataItem" 
          @bind-SelectedItems="selectedRows" 
          MultiSelection="true"
          Hover="true">
    <HeaderContent>
        <MudTh>
            <MudCheckBox T="bool" CheckedChanged="@((bool isChecked) => context.ToggleAllSelection(isChecked))"/>
        </MudTh>
        <MudTh>ID</MudTh>
        <MudTh>名称</MudTh>
    </HeaderContent>
    <RowTemplate>
        <MudTd>
            <MudCheckBox T="bool" Checked="@context.IsSelected(context.Item)"/>
        </MudTd>
        <MudTd>@context.Id</MudTd>
        <MudTd>@context.Name</MudTd>
    </RowTemplate>
</MudTable>

@* 操作按钮 *@
<MudButton Disabled="@(!selectedRows.Any())" 
           Variant="Variant.Filled" 
           Color="Color.Primary">
    批量删除
</MudButton>

@code {
    // 绑定的多选选中集合
    private HashSet<DataItem> selectedRows = new();
    // 其余表格数据、业务逻辑
}

踩坑提示:如果使用服务端分页、虚拟滚动功能,不要在分页请求回调里重置选中项绑定的字段,否则会导致选中状态丢失、禁用状态判断异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 04:57:18