我需要创建一个仅包含数字的TextBox,但是我做不到。我试过了:InputScope =“ Numbers”,但这仅适用于Mobile。我也尝试过TextChanging这个:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]"))
{
textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以阻止任何非数字输入,也可以仅过滤掉文本中的数字。
防止非数字输入
使用BeforeTextChanging事件:
<TextBox BeforeTextChanging="TextBox_OnBeforeTextChanging" />
Run Code Online (Sandbox Code Playgroud)
现在像这样处理:
private void TextBox_OnBeforeTextChanging(TextBox sender,
TextBoxBeforeTextChangingEventArgs args)
{
args.Cancel = args.NewText.Any(c => !char.IsDigit(c));
}
Run Code Online (Sandbox Code Playgroud)
该LINQ表达式将返回true,因此Cancel如果输入中遇到任何非数字字符,则将更改文本。
过滤非数字输入
使用TextChanging事件:
<TextBox TextChanging="TextBox_OnTextChanging" />
Run Code Online (Sandbox Code Playgroud)
并以这种方式处理:
private void TextBox_OnTextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
sender.Text = new String(sender.Text.Where(char.IsDigit).ToArray());
}
Run Code Online (Sandbox Code Playgroud)
此LINQ查询将过滤掉非数字字符,并string仅使用输入中的数字创建一个新字符。
最好使用TextChanging和BeforeTextChanging,因为它TextChanged发生得太晚了,所以看到文字暂时显示在屏幕上然后立即消失,会使用户感到困惑。