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

如何在Blazor中根据属性值动态设置图标的显示颜色?

在Blazor中根据属性值动态设置图标颜色

你可以通过两种简单方式实现根据SendToBoth属性切换图标的颜色:

方法一:内联样式绑定

直接在<span>标签的style属性中使用三元表达式,根据属性值设置颜色:

<span class="oi oi-arrow-thick-right" aria-hidden="true" style="@(forward.SendToBoth ? "color: #007bff;" : "color: #6c757d;")"></span>

这里用了Bootstrap原生主题色:#007bff是标准蓝色,#6c757d是标准灰色,你可以根据需求替换成自定义颜色值。

方法二:CSS类绑定(推荐)

先在组件的样式块中定义两个颜色类:

<style>
    .forward-icon-blue {
        color: #007bff;
    }
    .forward-icon-gray {
        color: #6c757d;
    }
</style>

然后在<span>标签中通过@class指令动态绑定类名:

<span class="oi oi-arrow-thick-right" 
      @class="@(forward.SendToBoth ? "forward-icon-blue" : "forward-icon-gray")" 
      aria-hidden="true"></span>

这种方式更利于后期维护,比如需要调整颜色或添加其他样式时,直接修改CSS类即可,不用改动HTML结构。

修改后的完整代码示例

<style>
    .forward-icon-blue {
        color: #007bff;
    }
    .forward-icon-gray {
        color: #6c757d;
    }
</style>

<tbody>
    @foreach (var forward in activeForwards)
    {
        <tr>
            <td>@forward.DisplayName</td>
            <td>@forward.PrimarySmtpAddress</td>
            <td>
                <span class="oi oi-arrow-thick-right" 
                      @class="@(forward.SendToBoth ? "forward-icon-blue" : "forward-icon-gray")" 
                      aria-hidden="true"></span>
                <button class="btn btn-primary" @onclick="() => HandleRemoveAction(forward)">X</button>
            </td>
            <td>@forward.ForwardToDisplay</td>
            <td>@forward.ForwardToEmail</td>
        </tr>
    }
</tbody>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 20:47:09