【发布时间】:2011-08-05 02:13:30
【问题描述】:
可能重复:
How do I get a TextBox to only accept numeric input in WPF?
以下代码不正确:
private void txtCode_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !AreAllValidNumericChars(e.Text);
}
private bool AreAllValidNumericChars(string str)
{
foreach (char c in str)
{
if (!Char.IsNumber(c)) return false;
}
return true;
}
和
private void txtCode_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !AreAllValidNumericChars(e.Text);
}
bool AreAllValidNumericChars(string str)
{
bool ret = true;
if (str == System.Globalization.NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.CurrencyGroupSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.CurrencySymbol |
str == System.Globalization.NumberFormatInfo.CurrentInfo.NegativeSign |
str == System.Globalization.NumberFormatInfo.CurrentInfo.NegativeInfinitySymbol |
str == System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.NumberGroupSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PercentDecimalSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PercentGroupSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PercentSymbol |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PerMilleSymbol |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PositiveInfinitySymbol |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PositiveSign)
return ret;
int l = str.Length;
for (int i = 0; i < l; i++)
{
char ch = str[i];
ret &= Char.IsDigit(ch);
}
return ret;
}
和
private override void txtCode_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
char c = e.Text.ToCharArray().First();
e.Handled = !(char.IsNumber(c) || char.IsControl(c));
}
还有.....
问题:Ctrl+V 复制/粘贴
什么是正确的代码?
【问题讨论】:
-
我相信你想知道的一切都在这个参考中:karlhulme.wordpress.com/2007/02/15/… 特别是,阅读最后一部分。
-
也许stackoverflow.com/questions/1268552/… 可以提供帮助。