MudTable - How to set cell color

318 Views Asked by At

I need a way to color a selected cell, e.g. if its value is greater than something. I know how to color an entire row in a table.

    private string TblRowStyle(Planowanie thing, int index)
    {
        if (thing.tydzien == tydzien)
        {
            return $"background: #D3D3D3";
        }
        else
        {
            return "";
        }
    }
   <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))" >

is coloring the entire row in the table. However, I need to set the colour of text in the cell conditionally, when the value is greater than something else.

1

There are 1 best solutions below

2
On BEST ANSWER

You can use the Style property on the the MudTd.

Here's how to do it inline.

<MudTd DataLabel="Position" Style="@(context.Position > 0? "background:green;":"background:red;")">@context.Position</MudTd>

And an example using a function to handle the logic.

<MudTable Items="@Elements.Take(4)" Hover="true" Breakpoint="Breakpoint.Sm" Loading="@_loading" LoadingProgressColor="Color.Info">
    <HeaderContent>
        <MudTh>Nr</MudTh>
        <MudTh>Sign</MudTh>
        <MudTh>Name</MudTh>
        <MudTh>Position</MudTh>
        <MudTh>Molar mass</MudTh>
    </HeaderContent>
    <RowTemplate>
        <MudTd DataLabel="Nr">@context.Number</MudTd>
        <MudTd DataLabel="Sign">@context.Sign</MudTd>
        <MudTd DataLabel="Name">@context.Name</MudTd>
        <MudTd DataLabel="Position" Style="@GetCellStyle(context.Position)">@context.Position</MudTd>
        <MudTd DataLabel="Molar mass">@context.Molar</MudTd>
    </RowTemplate>
</MudTable>

<MudSwitch @bind-Checked="_loading">Show Loading</MudSwitch>

@code { 
    private string GetCellStyle(int position)
    {
        if(position >0){
            return "background:green;";
        }else{
            return "background:red;";
        }
    }
}

MudBlazor snippet