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

如何在运行时设置Blazorise.DataGrid单元格的前景色?

解决方案

要实现根据温度值动态设置Temp.C.单元格的前景色,你可以通过Blazorise DataGrid的CellTemplate自定义单元格渲染逻辑,结合已有的颜色判断方法完成样式绑定。

修改后的完整代码

@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"/>
          <!-- 自定义TemperatureC列的单元格渲染逻辑 -->
          <DataGridNumericColumn Field="@nameof(WeatherForecast.TemperatureC)" Caption="C">
              <CellTemplate>
                  <span style="color:@getTempCForegroundColor(context.TemperatureC)">
                      @context.TemperatureC
                  </span>
              </CellTemplate>
          </DataGridNumericColumn>
          <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));
    }
}

关键说明

  1. 通过DataGridNumericColumn的CellTemplate插槽,完全自定义单元格的渲染内容
  2. 借助context对象获取当前行的WeatherForecast实例,读取TemperatureC的值
  3. 将getTempCForegroundColor方法返回的颜色值绑定到<span>的style属性,实现动态前景色效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 00:18:19