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

Avalonia:实现NumericUpDown失焦时解析文本并重置无效输入

问题描述

我使用如下的NumericUpDown控件:

<NumericUpDown Value="{Binding Samples}" ShowButtonSpinner="False" ParsingNumberStyle="Integer"/>

并在MainWindow.axaml.cs中编写了以下代码:

protected override void OnKeyDown(KeyEventArgs e)
{
    base.OnKeyDown(e);
    if (e.Key == Key.Enter) // includes Key.Return
            Focus();
}

这段代码实现按下回车键时输入框失去焦点。输入'100'并按回车时,控件能正常接收该值;但输入'100.0'或其他无效字符串时,按回车键控件不会失去焦点。我希望这种情况下输入能重置为用户开始输入前的原值,请问是否需要编写自定义验证器并在用户输入时调用?

解决方案

不需要额外编写自定义验证器,通过以下两种方式即可实现需求:

  • 调用控件内置的取消编辑方法:NumericUpDown自带CancelEdit()方法,执行后会自动将输入文本重置为当前绑定的Value原值,同时允许焦点正常转移。修改后的KeyDown事件代码如下:
protected override void OnKeyDown(KeyEventArgs e)
{
    base.OnKeyDown(e);
    if (e.Key == Key.Enter)
    {
        var focusedNumeric = FocusManager.GetFocusedElement(this) as NumericUpDown;
        focusedNumeric?.CancelEdit();
        Focus();
    }
}
  • 手动判断输入有效性并重置:如果需要更精细的控制,可以先解析输入文本判断是否符合整数要求,无效则手动将文本重置为当前Value的字符串形式:
protected override void OnKeyDown(KeyEventArgs e)
{
    base.OnKeyDown(e);
    if (e.Key == Key.Enter)
    {
        var focusedNumeric = FocusManager.GetFocusedElement(this) as NumericUpDown;
        if (focusedNumeric != null)
        {
            // 按整数格式验证输入
            if (!int.TryParse(focusedNumeric.Text, out _))
            {
                focusedNumeric.Text = focusedNumeric.Value.ToString();
            }
        }
        Focus();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 18:56:01