按行项目条件更改 MudBlazor table 背景颜色

Change MudBlazor table background color by row item condition

我正在尝试更改 mudblazor 中一行的颜色 table。问题是,我无法添加根据行元素的条件更改颜色的功能。

 <MudTable Items="@context.orderPositions" Context="AddressContext" Hover="true" Breakpoint="Breakpoint.Sm" Elevation="0" Style="background-color: @(AddressContext.OrderPositionStatus == PositionStatus.rdy ? yellowgreen : blue;">

这不是一个完整的答案,但在您的代码中,<MudTable> 中的样式会更改所有背景颜色。您需要确定 RenderFragment 的颜色,例如 <MudTd Style="background-color:yellow;</MudTd>"

https://try.mudblazor.com/snippet/cYcFEMkdVtcQQNnQ

我有一个解决方案,但感觉有点脏...

<RowTemplate>
                                    <MudTd DataLabel="Menge" Style="@(AddressContext.OrderPositionStatus == PositionStatus.rdy ? $"background:{Colors.BlueGrey.Darken4};" : $"background:{Colors.Cyan.Darken1};")">@AddressContext.orderItem.ItemQuantity</MudTd>
                                    <MudTd DataLabel="Itemcode" Style="@(AddressContext.OrderPositionStatus == PositionStatus.rdy ? $"background:{Colors.BlueGrey.Darken4};" : $"background:{Colors.Cyan.Darken1};")">@AddressContext.orderItem.ItemCode</MudTd>
                                    <MudTd DataLabel="Itemname" Style="@(AddressContext.OrderPositionStatus == PositionStatus.rdy ? $"background:{Colors.BlueGrey.Darken4};" : $"background:{Colors.Cyan.Darken1};")">@AddressContext.orderItem.ItemName</MudTd>
                                </RowTemplate>

如图所示,可以更改行模板内的颜色。所以上下文是可用的。它对每个 row/colum- 组合都很烦人,但最终它起作用了。

您可以:

<MudTable Items="@Items" Hover="true" RowStyleFunc="RowStyleFunc">

然后

private string RowStyleFunc(Item arg1, int index)
{
    switch (arg1.Title)
    {
        case string a when a.Contains("1/4"):
            return "background-color:blue";
        case string b when b.Contains("2/4"):
            return "background-color:red";          
        default: return "background-color:white";

    }
}

我希望能够隐藏默认情况下标记为删除的行项目,然后在启用切换开关时将它们显示为红色。所以在我的组件上我附加了一个开关:

<MudSwitch @bind-Checked="@blnShowDeleted" Color="Color.Warning">Show deleted</MudSwitch>

@Nadav Hury 的回答告诉我有关 RowStyleFunc 的信息,这让我找到了 MudBlazor 文档和 RowClassFunc,我认为这可能是更好的选择.所以我更改了 table 声明的代码:

<MudTable Items="objVmCustomers" RowClassFunc="ShowDeleted">

我在代码隐藏中创建了一个 ShowDeleted 方法 razor.cs class:

public string ShowDeleted(VmCustomer objVmCustomer, int index)
        {
        if(objVmCustomer.dtDeleted != null)
            {
            if (blnShowDeleted == true)
                {
                return "show-deleted";
                }

            return "hide-deleted";
            }

        return "";
        }

然后我创建了两个 CSS classes 来适应上面的代码:

.show-deleted td { --mud-palette-text-primary: red; }
.hide-deleted { display: none; visibility: collapse; }

这里有一个陷阱:你不能在 show-deleted 声明中直接使用 color:red; 因为 CSS 变量 --mud-palette-text-primary 将覆盖它。您必须覆盖 CSS 变量(我通过检查元素发现了这一点)。

通过使用对行内所有 TD 元素进行操作的 CSS class,这克服了 @T0bi 在使用多个 [=26= 时抱怨的 'dirtiness' ]样式属性。