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

如何修改MudDataGrid行中被点击的MudBlazor按钮颜色?

解决思路

核心思路是利用Blazor的数据驱动特性,通过绑定行数据的状态来控制按钮样式,而非直接操作DOM元素:

  1. 给行数据模型添加状态属性
    在你的PickListLine类中新增一个布尔属性,用来标记该行的短缺报告是否已提交成功:

    public class PickListLine
    {
        // 原有属性(SalesOrderRef、LineNumber等)...
        public bool IsShortageReported { get; set; } = false;
    }
    
  2. 绑定按钮的颜色和禁用状态到状态属性
    修改MudButton的Color和Disabled属性,根据当前行的IsShortageReported状态动态切换:

    <MudButton Size="Size.Large" 
               Variant="@Variant.Filled" 
               StartIcon="@Icons.Material.Filled.DoNotDisturbOn" 
               Color="@(context.Item.IsShortageReported ? Color.Success : Color.Primary)"
               Disabled="@context.Item.IsShortageReported"
               OnClick="@(x => AddShortage(PickList.PickListId, context.Item))">
        Shortage
    </MudButton>
    

    这里把原有的context.Item.LineNumber改成直接传递context.Item,方便后续直接修改该行的状态。

  3. 在API调用成功后更新状态
    修改AddShortage方法,当API请求成功时,将对应行的IsShortageReported设为true,Blazor会自动触发UI更新:

    private async Task AddShortage(int pickListId, PickListLine line)
    {
        try
        {
            // 发起API请求
            var response = await _yourApiService.ReportShortage(pickListId, line.LineNumber);
            if (response.IsSuccessStatusCode)
            {
                // 更新行状态,UI会自动同步
                line.IsShortageReported = true;
                // 若遇到UI未自动更新的情况,可手动调用
                // StateHasChanged();
            }
        }
        catch (Exception ex)
        {
            // 处理API请求异常
        }
    }
    
  4. 可选:添加加载状态避免重复点击
    如果API请求耗时较长,可以给模型再加一个IsSubmitting属性,控制按钮的加载状态:

    public class PickListLine
    {
        // 原有属性...
        public bool IsShortageReported { get; set; } = false;
        public bool IsSubmitting { get; set; } = false;
    }
    

    按钮绑定新增状态:

    <MudButton ... 
               Disabled="@(context.Item.IsShortageReported || context.Item.IsSubmitting)"
               Loading="@context.Item.IsSubmitting">
        Shortage
    </MudButton>
    

    方法中更新状态逻辑:

    private async Task AddShortage(int pickListId, PickListLine line)
    {
        if (line.IsSubmitting || line.IsShortageReported) return;
        line.IsSubmitting = true;
        try
        {
            var response = await _yourApiService.ReportShortage(pickListId, line.LineNumber);
            if (response.IsSuccessStatusCode)
            {
                line.IsShortageReported = true;
            }
        }
        catch (Exception ex)
        {
            // 处理异常
        }
        finally
        {
            line.IsSubmitting = false;
        }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 01:27:46