如何让WinUI 3中的TextBox仅接受数值输入?
WinUI 3 TextBox 仅接受数字输入的实现方案
WinUI 3 中没有 WPF 的KeyPress事件,以下是两种适配 WinUI 3 的实现方式:
方法一:使用 TextChanging 事件(推荐,覆盖所有输入场景)
这个事件能拦截所有文本变更操作(包括键盘输入、粘贴、拖拽等),相比仅处理键盘事件的方案更全面可靠。
private void NumericTextBox_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args) { // 记录当前光标位置,避免过滤后光标错位 int cursorPosition = sender.SelectionStart; int selectedLength = sender.SelectionLength; // 只保留数字和控制字符(如退格、删除) string filteredText = new string(sender.Text.Where(c => char.IsDigit(c) || char.IsControl(c)).ToArray()); if (filteredText != sender.Text) { sender.Text = filteredText; // 恢复光标位置,确保用户体验 sender.SelectionStart = Math.Min(cursorPosition, filteredText.Length); sender.SelectionLength = 0; } }
方法二:使用 KeyDown 事件(仅处理键盘输入)
如果只需要限制键盘输入的内容,可以通过KeyDown事件结合按键状态判断来实现:
using Windows.UI.Core; using Windows.System; private void NumericTextBox_KeyDown(object sender, KeyRoutedEventArgs e) { // 允许控制类按键(退格、删除、方向键等) if (e.Key is VirtualKey.Back or VirtualKey.Delete or VirtualKey.Left or VirtualKey.Right or VirtualKey.Up or VirtualKey.Down) { return; } // 判断是否为数字键(主键盘+小键盘) bool isDigitKey = e.Key is >= VirtualKey.Number0 and <= VirtualKey.Number9 or >= VirtualKey.NumberPad0 and <= VirtualKey.NumberPad9; // 检查是否按下Shift键(避免输入数字键对应的符号) CoreWindow currentWindow = CoreWindow.GetForCurrentThread(); bool isShiftPressed = (currentWindow.GetKeyState(VirtualKey.Shift) & VirtualKeyStates.Shift) == VirtualKeyStates.Shift; // 非数字键或按下Shift时,拦截输入 if (!isDigitKey || isShiftPressed) { e.Handled = true; } }
注意:方法二仅能拦截键盘输入,无法处理粘贴、拖拽等非键盘方式的非法输入,因此更推荐使用方法一。
内容的提问来源于stack exchange,提问作者cptalpdeniz
相关产品推荐
相关产品推荐

