【发布时间】:2010-10-25 18:32:33
【问题描述】:
我需要一个只有用户可以输入整数的文本框。但是用户不能输入零。即,他可以输入 10,100 等。而不仅仅是 0。 如何在 KeyDown 中制作事件?
【问题讨论】:
-
我认为您对问题的标记令人困惑,因为您有 Winforms,但需要 WPF 答案。
标签: c# wpf forms input-filtering
我需要一个只有用户可以输入整数的文本框。但是用户不能输入零。即,他可以输入 10,100 等。而不仅仅是 0。 如何在 KeyDown 中制作事件?
【问题讨论】:
标签: c# wpf forms input-filtering
使用int.TryParse 将文本转换为数字并检查该数字是否不为0。使用Validating 事件进行检查。
// this goes to you init routine
textBox1.Validating += textBox1_Validating;
// the validation method
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text.Length > 0)
{
int result;
if (int.TryParse(textBox1.Text, out result))
{
// number is 0?
e.Cancel = result == 0;
}
else
{
// not a number at all
e.Cancel = true;
}
}
}
编辑:
好的,既然你使用 WPF,你应该看看如何实现validation the WPF way。下面是一个实现上述逻辑的验证类:
public class StringNotZeroRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (textBox1.Text.Length == 0)
return new ValidationResult(true, null);
int result;
if (int.TryParse(textBox1.Text, out result))
{
// number is 0?
if (result == 0)
{
return new ValidationResult(false, "0 is not allowed");
}
}
else
{
// not a number at all
return new ValidationResult(false, "not a number");
}
return new ValidationResult(true, null);
}
}
【讨论】:
您计划执行此操作的方式对用户来说非常烦人。您在猜测用户想要输入的内容,然后根据您的猜测采取行动,但您可能会大错特错。
它也有漏洞,例如用户可以输入“10”然后删除“1”。或者他可以粘贴一个“0”——你确实允许粘贴,不是吗?
所以我的解决方案是:让他以任何他喜欢的方式输入他喜欢的任何数字,并且仅在他完成后验证输入,例如,当输入失去焦点时。
【讨论】:
这是主题的另一个变体:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
char newChar = Convert.ToChar(e.KeyValue);
if (char.IsControl(newChar))
{
return;
}
int value;
e.SuppressKeyPress = int.TryParse((sender as TextBox).Text + newChar.ToString(), out value) ? value == 0 : true;
}
【讨论】:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (textBox1.Text == "" && e.KeyChar == '0')
{
e.Handled = true;
return;
}
if (e.KeyChar < '0' || e.KeyChar > '9')
{
e.Handled = true;
return;
}
}
不是很好,但它有效
【讨论】:
为什么不使用 NumericUpDown 并进行以下设置:
upDown.Minimum = 1;
upDown.Maximum = Decimal.MaxValue;
【讨论】: