c# - Restrict characters in TextBox of UWP apps
问题描述
My TextBox should only allow what you can type in a basic calculator like numbers 0 to 9
and % * / - + . ( )
So, no letters and other characters. I tried the following from another SO thread but it's not doing anything. You can still type pretty much everything in the TextBox.
private void textBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
if ((e.Key < VirtualKey.NumberPad0 || e.Key > VirtualKey.NumberPad9) & (e.Key < VirtualKey.Number0 || e.Key > VirtualKey.Number9))
{
e.Handled = true;
}
}
解决方案
private void textBox_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
if (!Regex.IsMatch(sender.Text, @"^-?\d+\.?\d+[-+*\/]-?\d+\.?\d+$") && sender.Text != "")
{
int position = sender.SelectionStart - 1;
sender.Text = sender.Text.Remove(position, 1);
sender.SelectionStart = position;
}
}
推荐阅读
- python - 找到具有 0 个样本的数组 (shape=(0, 1)),而 MinMaxScaler 要求最小值为 1
- android - 我正在使用 Flutter 创建一个呼叫应用程序,我想隐藏联系号码并只显示姓名
- python - 无法正确绘制 2 y 系列及其相应日期在 x 轴上的绘图?
- c - 指定的初始化程序可以合法地引用它在 C99 中初始化的变量吗?
- javascript - 如何在 React.js 中返回对象
- python - 如何在单个窗口中绘制多个 seaborn `distplot`?
- angular - Angular - 在焦点上显示/隐藏元素
- c# - ASP.NET Core MVC 请求返回 404
- python - Cartopy 是否会导致 Matplotlib clabels 成为 NoneType 对象?很奇怪的bug
- c# - C# Selenium - 在不重启 Chrome 浏览器的情况下更新代理