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

MudNumericField设置Immediate=true后千位分隔符不实时生效求助

解决MudNumericField实时千位分隔符不生效的问题

针对你遇到的MudNumericField设置Immediate="true"后,输入时无法实时插入千位分隔符、仅失焦时才生效的问题,可通过以下两种方案解决:

方法一:启用Mask属性(推荐)

MudNumericField自带的Mask属性可直接实现实时千位分隔符格式化,配置简单且无需额外逻辑:

@using System.Globalization

<MudNumericField 
    Immediate="true" 
    Format="#,##0" 
    Culture="@_vn" 
    @bind-Value="_value"
    Mask="numeric"
    MaskPlaceholder=""
/>

@code {
    public CultureInfo _vn = CultureInfo.GetCultureInfo("vi-VN");
    public decimal? _value { get; set; }
}

设置Mask="numeric"后,组件会在用户输入过程中自动插入千位分隔符,同时保留Immediate="true"的实时值绑定特性。

方法二:监听OnInput事件手动处理

若因版本或需求限制无法使用Mask属性,可通过监听OnInput事件手动格式化数值并维护光标位置:

@using System.Globalization
@using System.Text.RegularExpressions

<MudNumericField 
    Immediate="true" 
    Format="#,##0" 
    Culture="@_vn" 
    @bind-Value="_value"
    @ref="_numericRef"
    OnInput="HandleInput"
/>

@code {
    private MudNumericField<decimal?> _numericRef;
    public CultureInfo _vn = CultureInfo.GetCultureInfo("vi-VN");
    public decimal? _value { get; set; }

    private void HandleInput(ChangeEventArgs e)
    {
        if (e.Value is string inputStr)
        {
            // 清理输入中的非数字字符(保留负号)
            var cleanedInput = Regex.Replace(inputStr, @"[^\d-]", "");
            if (decimal.TryParse(cleanedInput, out decimal parsedValue))
            {
                // 保存当前光标位置
                var cursorPos = _numericRef.Element.Value.SelectionStart;
                // 更新值触发格式化
                _value = parsedValue;
                // 渲染后恢复光标位置,避免跳转
                InvokeAsync(() =>
                {
                    StateHasChanged();
                    _numericRef.Element.Value.SelectionStart = cursorPos;
                    _numericRef.Element.Value.SelectionEnd = cursorPos;
                });
            }
        }
    }
}

注意事项

  • 优先确保使用最新稳定版的MudBlazor,旧版本可能存在实时格式化相关的bug
  • 方法二的示例仅针对整数场景,如需支持小数,可调整正则表达式和解析逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 20:12:05