我有一个TextBox
,我希望它只是数字。因此,我用谷歌搜索并找到了this stackoverflow帖子,这对我帮助已经很多了。但是,当我输入20下面的内容时,我希望现在仅限数字的文本框显示警告。首先,我尝试了事件OnTextInput
,但在没有成功之后,我尝试在与事件相同的事件中处理它。数字内容OnPreviewTextInput
。我对两者使用了相同的代码。
if (!char.IsDigit(e.Text, e.Text.Length - 1))
{
var text = e.Text;
int num;
var success = int.TryParse(text, out num);
if (!success)
return;
if (num <= 20)
{
if (MessageBox.Show("Are you sure you want to go underneath 20?",
"... You sure?", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) ==
MessageBoxResult.Yes)
e.Handled = true;
else
{
num++;
textBox.Text = num.ToString();
}
}
e.Handled = true;
}
答案 0 :(得分:1)
使用TextChanged Handler 要在它改变时捕获,然后制作过滤器。
执行后可能如下所示:
private void yourTextBox_TextChanged(object sender, EventArgs e)
{
if (!char.IsDigit(e.Text, e.Text.Length - 1))
{
var text = e.Text;
int num;
var success = int.TryParse(text, out num);
if (!success)
return;
if (num <= 20)
{
if (
MessageBox.Show("Are you sure you want to go underneath 20?",
"... You sure?", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) ==
MessageBoxResult.Yes)
e.Handled = true;
else
{
num++;
textBox.Text = num.ToString();
}
}
e.Handled = true;
}
}
答案 1 :(得分:1)
为什么不处理KeyDown
事件?
private void txtNumeric_KeyDown(object sender, KeyEventArgs e)
{
e.Handled = !char.IsDigit(e.KeyChar);
if (Int32.Parse(sender.Text) <= 20)
{
if (
MessageBox.Show("Are you sure you want to go underneath 20?",
"... You sure?", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) ==
MessageBoxResult.Yes)
e.Handled = true;
else
{
num++;
textBox.Text = num.ToString();
}
}