我有一个带有文本框的Silverlight应用程序,其输入我只想限制为十进制数。在网上搜索我遇到了以下可能的解决方案(好奇地在不同的地方,不同的人声称同一行代码的作者) 它似乎运作良好,除了在输入至少1个数字后,它将允许输入大写或小写字母'd',我无法弄清楚为什么会这样,因此无法弄清楚如何防止这种情况发生。有谁能请提供解决方案。非常感谢。
private void Unit_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab)
{
}
var thisKeyStr = "";
if (e.PlatformKeyCode == 190 || e.PlatformKeyCode == 110)
{
thisKeyStr = ".";
}
else
{
thisKeyStr = e.Key.ToString().Replace("D", "").Replace("NumPad", "");
}
var s = (sender as TextBox).Text + thisKeyStr;
var rStr = "^[0-9]+[.]?[0-9]*$";
var r = new Regex(rStr, RegexOptions.IgnoreCase);
e.Handled = !r.IsMatch(s);
}
答案 0 :(得分:2)
您可以尝试以下方法:
else
替换为else if (e.Key != Key.D)
或设置Handled
属性,如下所示:
e.Handled = !r.IsMatch(s) || string.IsNullOrEmpty(thisKeyStr);
// also possible:
e.Handled = !r.IsMatch(s) || e.Key == Key.D;
答案 1 :(得分:2)
这是一个更简单的代码优化。没有对象创建;没有字符串比较和NO正则表达式验证
private static void TextBox_KeyDown(object sender, KeyEventArgs e)
{
//platform code for Hyphen which is not same as Subtract symbol but in our case both give same meaning
const int KEYCODE_Hyphen_OnKeyboard = 189;
const int KEYCODE_Dot_OnKeyboard = 190;
const int KEYCODE_Dot_OnNumericKeyPad = 110;
e.Handled = !(
(!( //No modifier key must be pressed
(Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift
|| (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control
|| (Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt
)
&& ( //only these keys are supported
(e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9)
|| e.Key == Key.Subtract || e.Key == Key.Add || e.Key == Key.Decimal
|| e.Key == Key.Home || e.Key == Key.End || e.Key == Key.Delete
|| e.Key == Key.Tab || e.Key == Key.Enter || e.Key == Key.Escape || e.Key == Key.Back
|| (e.Key == Key.Unknown && (
e.PlatformKeyCode == KEYCODE_Hyphen_OnKeyboard
|| e.PlatformKeyCode == KEYCODE_Dot_OnKeyboard || e.PlatformKeyCode == KEYCODE_Dot_OnNumericKeyPad
)
)
)
)
);
}
答案 2 :(得分:0)
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
bool isDigit = e.Key >= Key.D0 && e.Key < Key.D9 || e.Key == Key.NumPad0 || e.Key == Key.NumPad1 || e.Key == Key.NumPad2 || e.Key == Key.NumPad3 || e.Key == Key.NumPad4 || e.Key == Key.NumPad5 || e.Key == Key.NumPad6 ||
e.Key == Key.NumPad7 || e.Key == Key.NumPad8 || e.Key == Key.NumPad9 ||e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Left || e.Key == Key.Right;
if (isDigit) { }
else
e.Handled = true;
}