blazorruntimeblazorise

How to set Blasorise.DataGrid cell's forecolor at run-time?


How to set Blazorise.DataGrid cell's forecolor at run-time? I wanted the forecolor of the sample weather forecast app's Temp.C. cells to be set depending on their values, for example,

    @page "/fetchdata"

    <PageTitle>Weather forecast</PageTitle>

    @using BlazoriseDemo.Data
    @using Blazorise;

    @inject WeatherForecastService ForecastService

    <h1>Weather forecast</h1>

    <p>This component demonstrates fetching data from a service.</p>

    @if (forecasts == null)
    {
        <p><em>Loading...</em></p>
    }
    else
    {

        <DataGrid TItem="WeatherForecast"
              Data="@forecasts"
              @bind-SelectedRow="@selectedForecast"
              Responsive>
    
              <DataGridColumn Field="@nameof(WeatherForecast.Date)" Caption="Date"/>
              <DataGridNumericColumn Field="@nameof(WeatherForecast.TemperatureC)" Caption="C" />
              <DataGridNumericColumn Field="@nameof(WeatherForecast.TemperatureF)" Caption="F" />
              <DataGridColumn Field="@nameof(WeatherForecast.Summary)" Caption="Summary"/>

        </DataGrid>

    }

    @code {
        private WeatherForecast selectedForecast;
        private WeatherForecast[]? forecasts;

        protected string getTempCForegroundColor(int temperatureC)
        {
            var color = "blue";
            if (temperatureC >= 0 && temperatureC < 20) color = "orange";
            else if (temperatureC > 20) color = "red";
            return color;
        }

        protected override async Task OnInitializedAsync()
        {
            forecasts = await new WeatherForecastService().GetForecastAsync(new DateTime(2022,07,1));
        }
    }


Solution

  • Multiple solutions:

    ex.

    <DataGridColumn CellStyle="@((item)=> {if(item.TemperatureC > 19){return "color: #f00";} else { return "color: #00f";}})" [...] />
    

    (but using inline style is often a bad practice)

    ex.

    <DataGridColumn CellClass="@((item)=> {if(item.TemperatureC > 19){return "color-hot";} else { return "color-cold";}})" [...] />
    

    and then you have a .css for utility classes (color-hot will set the color to red), quite like bootstrap

    <DataGridColumn [...]>
        <DisplayTemplate>
            <span class="(@context.TemperatureC > 19 ? "color-hot" : "color-cold")">
                @context.TemperatureC
            </span>
        </DisplayTemplate>
    </DataGridColumn>