ShamilS
ShamilS

Reputation: 1614

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));
        }
    }

Upvotes: 0

Views: 474

Answers (1)

Vertus
Vertus

Reputation: 112

Multiple solutions:

  • use CellStyle attribute of DataGridColumn to set the inline style regarding the row.

ex.

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

(but using inline style is often a bad practice)

  • use CellClass attribute of DataGridColumn to set an utility class to the cell regarding the row.

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

  • use DisplayTemplate to customize the content of the cell, where you can use the "context" variable that represent current row item:
<DataGridColumn [...]>
    <DisplayTemplate>
        <span class="(@context.TemperatureC > 19 ? "color-hot" : "color-cold")">
            @context.TemperatureC
        </span>
    </DisplayTemplate>
</DataGridColumn>

Upvotes: 3

Related Questions