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

Blazor Server应用中如何根据Razor.cs变量动态修改文本颜色

解决Blazor Server动态修改文本颜色的问题

步骤1:调整数据结构,保存每条消息的类型

你当前的List<string>仅存储文本内容,无法对应每条消息的类型,因此需要创建一个数据类来同时存储文本和类型:

在你的Razor.cs文件中添加:

public class AlarmItem
{
    public string Text { get; set; }
    public string Type { get; set; }
}

// 替换原有的List<string>
public List<AlarmItem> PLC_alarm_text = new List<AlarmItem>();

然后修改function方法,添加消息时同时记录类型:

public void function()
{
    if(alarm_text_Type == "error")
    {
        PLC_alarm_text.Add(new AlarmItem { Text = "some error text", Type = "error" });
    }
    if(alarm_text_Type == "message")
    {
        PLC_alarm_text.Add(new AlarmItem { Text = "some message text", Type = "message" });
    }
    
    // 如果该方法在UI事件外调用(比如定时器、外部回调),需触发状态更新
    // StateHasChanged();
}

步骤2:动态绑定样式(两种可选方案)

方案一:使用CSS类切换

先在CSS文件中定义不同状态的样式:

.alarm_color {
    color: black; /* 默认黑色 */
}
.alarm_color.error {
    color: red; /* error类型用红色 */
}

然后在Razor页面中循环渲染时,根据消息类型添加对应的类:

<table>
    @foreach (var item in PLC_alarm_text)
    {
        <tr>
            <td class="alarm_color @(item.Type == "error" ? "error" : "")">@item.Text</td>                    
        </tr>
    }
</table>

方案二:直接绑定style属性

如果不想新增CSS类,可以直接在元素上动态绑定颜色值:

<table>
    @foreach (var item in PLC_alarm_text)
    {
        <tr>
            <td style="color: @(item.Type == "error" ? "red" : "black")">@item.Text</td>                    
        </tr>
    }
</table>

注意事项

  • 如果function方法是在UI事件之外调用的(比如后台定时器、外部API回调),需要手动调用StateHasChanged()方法通知Blazor更新UI。
  • 推荐使用foreach循环遍历集合,比for循环更符合Blazor的组件渲染逻辑,也更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 01:57:32