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

WPF中不使用TextChanged事件实现TextBox输入点替换为逗号

WPF TextBox实现句点自动替换为逗号+输入合法性校验

核心实现原理

WPF的PreviewTextInput属于隧道路由事件,会在文本实际写入TextBox控件之前触发,完全满足「句点替换完成后再执行业务TextChanged逻辑」的时序要求。由于TextCompositionEventArgs.Text是只读属性,无法像WinForms那样直接修改输入字符,因此检测到输入为句点时,手动向TextBox插入替换后的逗号,同时拦截原始句点输入即可。退格键不会触发PreviewTextInput事件,默认即可正常使用,无需额外放行。

完整实现代码

XAML部分

和原有写法保持一致即可,不需要额外绑定其他事件:

<TextBox PreviewTextInput="NumberValidationTextBox" />

后台事件处理代码

using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
    TextBox textBox = (TextBox)sender;
    
    // 拦截并替换输入的句点
    if (e.Text == ".")
    {
        e.Handled = true;
        int insertPosition;

        // 处理存在选中文本的场景:替换选中内容
        if (textBox.SelectionLength > 0)
        {
            int selectStart = textBox.SelectionStart;
            textBox.Text = textBox.Text
                .Remove(selectStart, textBox.SelectionLength)
                .Insert(selectStart, ",");
            insertPosition = selectStart + 1;
        }
        else
        {
            // 无选中内容时直接在光标位置插入
            int caretIndex = textBox.CaretIndex;
            textBox.Text = textBox.Text.Insert(caretIndex, ",");
            insertPosition = caretIndex + 1;
        }

        // 还原光标位置,避免光标跳转到文本末尾
        textBox.CaretIndex = insertPosition;
        return;
    }

    // 输入合法性校验:仅允许输入数字、逗号
    Regex regex = new Regex("[^0-9,]+");
    e.Handled = regex.IsMatch(e.Text);
}

补充说明

  • 所有替换操作均在文本写入TextBox前完成,后续TextChanged事件触发时,获取到的文本已经完成句点替换,无需调整原有绑定在TextChanged上的业务逻辑。
  • 若需要覆盖粘贴场景,可额外绑定DataObject.Pasting附加事件,将粘贴内容中所有.替换为,后再插入文本框即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.31 06:19:28