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

Blazor FluentUI:Swatch未转十六进制,开关颜色设置异常求助

修改Fluent UI开关关闭状态下的圆点颜色问题

我想要修改Fluent UI开关的样式,使其在关闭状态下的圆点颜色不同。但当前代码运行后,CSS元素的值被设置为[object Object],而非预期的十六进制代码,请问如何修复?

我的代码

HTML代码

<FluentSwitch @ref="ref1"/>

后台C#代码

private Microsoft.FluentUI.AspNetCore.Components.DesignTokens.Swatch customColor = "#0473ce".ToSwatch();

[Inject]
private NeutralForegroundRest neutralForegroundRest { get; set; } = default!;

private FluentSwitch? ref1;

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        await neutralForegroundRest.SetValueFor(ref1!.Element, customColor);
    }
}

问题现象

该代码似乎能触发CSS元素值的更新,但实际将颜色值改为了[object Object],而非预期的#0473ce:

开关样式异常截图

修复方案

方案1:直接传递十六进制颜色字符串

问题根源在于直接传递Swatch对象给SetValueFor方法,该方法在转换为CSS值时将对象序列化为了[object Object]。只需改为传递十六进制颜色字符串即可:

private string customColor = "#0473ce";

[Inject]
private NeutralForegroundRest neutralForegroundRest { get; set; } = default!;

private FluentSwitch? ref1;

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        await neutralForegroundRest.SetValueFor(ref1!.Element, customColor);
    }
}

方案2:使用Swatch的CSS字符串表示

如果需要保留Swatch对象,可以调用其ToCssString()方法获取对应的CSS颜色值:

private Microsoft.FluentUI.AspNetCore.Components.DesignTokens.Swatch customColor = "#0473ce".ToSwatch();

[Inject]
private NeutralForegroundRest neutralForegroundRest { get; set; } = default!;

private FluentSwitch? ref1;

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        await neutralForegroundRest.SetValueFor(ref1!.Element, customColor.ToCssString());
    }
}

方案3:通过CSS直接修改样式

无需后台代码,直接通过CSS自定义关闭状态下的圆点颜色:

::deep .fluent-switch[aria-checked="false"] .switch-thumb {
    background-color: #0473ce !important;
}

内容的提问来源于stack exchange,提问作者Yannic van de Kuit

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 10:55:14