using System.Text.RegularExpressions; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace UILib { public class NumberInput : TextBox { public NumberInput() { DataObject.AddPastingHandler(this, OnPasting); // 禁用输入法 InputMethod.SetIsInputMethodEnabled(this, false); // 设置输入法模式为字母 InputScope inputScope = new InputScope(); InputScopeName inputScopeName = new InputScopeName(); inputScopeName.NameValue = InputScopeNameValue.Number; inputScope.Names.Add(inputScopeName); this.InputScope = inputScope; } static NumberInput() { DefaultStyleKeyProperty.OverrideMetadata(typeof(NumberInput), new FrameworkPropertyMetadata(typeof(NumberInput))); } public override void OnApplyTemplate() { base.OnApplyTemplate(); } protected override void OnPreviewTextInput(TextCompositionEventArgs e) { // 允许输入数字、负号和小数点 Regex regex = new Regex(@"^-?\d*\.?\d*$"); string segment = e.Text == "." ? ".0" : e.Text; string newText = this.Text.Insert(this.CaretIndex, segment); // 检查是否已经有负号,如果有则不允许再输入负号 if (e.Text == "-" && this.Text.Contains("-")) { e.Handled = true; return; } // 检查是否已经有小数点,如果有则不允许再输入小数点 if (e.Text == "." && this.Text.Contains(".")) { e.Handled = true; return; } //else if (e.Text == ".") { // e.Text = ".0"; //} //regex = new Regex(@"^-?\d*\.?\d*$|^-?\.\d*$|^-?\d+\.$"); // 验证完整的新文本是否符合数字格式 if (!regex.IsMatch(newText)) { e.Handled = true; return; } base.OnPreviewTextInput(e); } protected override void OnPreviewKeyDown(KeyEventArgs e) { // 允许使用退格键和删除键 if (e.Key == Key.Back || e.Key == Key.Delete) { base.OnPreviewKeyDown(e); return; } // 允许复制粘贴等快捷键 if (Keyboard.Modifiers == ModifierKeys.Control && (e.Key == Key.C || e.Key == Key.V || e.Key == Key.X)) { base.OnPreviewKeyDown(e); return; } } private void OnPasting(object sender, DataObjectPastingEventArgs e) { if (e.DataObject.GetDataPresent(typeof(string))) { string text = (string)e.DataObject.GetData(typeof(string)); Regex regex = new Regex(@"^-?\d*\.?\d*$"); if (!regex.IsMatch(text)) { e.CancelCommand(); } } } } }