问题描述
我需要创建一个仅包含数字的TextBox,但是我做不到.我试过了:InputScope ="Numbers",但这仅适用于Mobile.我也尝试过 TextChanging
:
I need to create a TextBox with only numbers but I couldn't do.I have tried to put : InputScope = "Numbers" but this only work on Mobile.Also I have tried on TextChanging
this:
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);
}
}
推荐答案
您可以阻止任何非数字输入,也可以只过滤掉文本中的数字.
You can either prevent any non-numeric input whatsoever, or just filter out digits in the text.
防止非数字输入
使用 BeforeTextChanging
事件:
<TextBox BeforeTextChanging="TextBox_OnBeforeTextChanging" />
现在处理如下:
private void TextBox_OnBeforeTextChanging(TextBox sender,
TextBoxBeforeTextChangingEventArgs args)
{
args.Cancel = args.NewText.Any(c => !char.IsDigit(c));
}
此LINQ表达式将返回 true
,因此,如果输入中遇到任何非数字字符,则取消
更改文本.
This LINQ expression will return true
and hence Cancel
the text change in case it encounters any non-digit character in the input.
过滤非数字输入
使用 TextChanging
事件:
<TextBox TextChanging="TextBox_OnTextChanging" />
并以这种方式处理:
private void TextBox_OnTextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
//Save the position of the selection, to prevent the cursor to jump to the start
int pos = sender.SelectionStart;
sender.Text = new String(sender.Text.Where(char.IsDigit).ToArray());
sender.SelectionStart = pos;
}
此LINQ查询将过滤掉非数字字符并仅使用输入中的数字来创建新的 string
.
This LINQ query will filter out non-digit characters and create a new string
only with the digits in the input.
最好使用 TextChanging
和 BeforeTextChanging
,因为 TextChanged
发生得太晚了,所以看到临时显示的字符会使用户感到困惑在屏幕上,然后立即消失.
It is preferable to use TextChanging
and BeforeTextChanging
, because TextChanged
occurs too late, so the user would be confused by seeing characters temporarily display on the screen and immediately disappearing.
这篇关于仅包含数字的文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!