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

MudTable单元格颜色设置:如何按值条件设置单元格文本颜色

在MudTable中为指定单元格设置条件文本颜色

下面提供两种实用方法,实现根据单元格值动态设置文本颜色:

方法一:利用列的CellStyleFunc属性

这种方式适合对整列单元格统一设置条件样式,无需自定义模板:

1. 编写样式判断方法

在代码文件中添加方法,根据目标字段值和列索引返回对应样式:

private string GetCellTextStyle(Planowanie item, int columnIndex)
{
    // 示例:判断第2列(索引从0开始)的Wartosc字段,大于100时文本设为红色
    if (columnIndex == 2 && item.Wartosc > 100)
    {
        return "color: #ff0000;";
    }
    return "";
}

2. 在MudTable列中绑定CellStyleFunc

在HTML的目标列上指定CellStyleFunc属性:

<MudTable T="Planowanie" Items="@planowanie" FixedHeader="true" Height="@(fixed_header ? "800px" : "")" 
          CustomHeader="true" CustomFooter="true" Dense="true" Hover="true" Bordered="true" 
          Striped="true" Breakpoint="Breakpoint.Sm" MultiSelection="false" 
          RowStyleFunc="@((item, idx) => TblRowStyle(item, idx))">
    <Columns>
        <MudTblColumn Field="nameof(Planowanie.tydzien)" Title="Tydzien" />
        <!-- 绑定样式函数到目标列 -->
        <MudTblColumn Field="nameof(Planowanie.Wartosc)" Title="Wartosc" 
                      CellStyleFunc="@((item, idx) => GetCellTextStyle(item, idx))" />
        <MudTblColumn Field="nameof(Planowanie.InnePole)" Title="Inne Pole" />
    </Columns>
</MudTable>

方法二:自定义单元格模板

如果需要更灵活的控制(比如添加额外元素或更复杂的判断逻辑),可以使用自定义单元格模板:

1. 编写文本颜色判断方法

private string GetTextColor(int value)
{
    // 示例:值大于100时文本变红,否则用默认颜色
    return value > 100 ? "color: #ff0000;" : "";
}

2. 在列中使用CellTemplate

直接在目标列的模板里根据值设置样式:

<MudTable T="Planowanie" Items="@planowanie" FixedHeader="true" Height="@(fixed_header ? "800px" : "")" 
          CustomHeader="true" CustomFooter="true" Dense="true" Hover="true" Bordered="true" 
          Striped="true" Breakpoint="Breakpoint.Sm" MultiSelection="false" 
          RowStyleFunc="@((item, idx) => TblRowStyle(item, idx))">
    <Columns>
        <MudTblColumn Field="nameof(Planowanie.tydzien)" Title="Tydzien" />
        <MudTblColumn Title="Wartosc">
            <CellTemplate>
                <!-- 根据字段值动态设置span的样式 -->
                <span style="@GetTextColor(Context.Item.Wartosc)">
                    @Context.Item.Wartosc
                </span>
            </CellTemplate>
        </MudTblColumn>
        <MudTblColumn Field="nameof(Planowanie.InnePole)" Title="Inne Pole" />
    </Columns>
</MudTable>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 20:02:50