【发布时间】:2014-04-08 17:38:21
【问题描述】:
我需要验证来检查按下的键是否为数字。我尝试了不同的代码,但他们无法帮助我。在文本框中,如果用户按Shift+numbers,它会显示特殊字符,如!,@,#......我需要验证Shift + key down event。
//代码
private void txtNumericTextbox_KeyDown(object sender, KeyEventArgs e)
{
try
{
if (e.Key < Key.D0 || e.Key > Key.D9)
{
if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9)
{
if (e.Key != Key.Back)
{
txtNumericTextbox_.BorderBrush = new SolidColorBrush(Colors.Red);
lblErrorMessage.Visibility = Visibility.Visible;
lblErrorMessage.Text = "Please Enter Numbers Only";
}
else
{
txtNumericTextbox_.BorderBrush = new SolidColorBrush(Colors.DarkGray);
lblErrorMessage.Visibility = Visibility.Collapsed;
lblErrorMessage.Text = "";
}
}
}
}
}
我怎样才能做到这一点?
【问题讨论】:
-
通常当我处理数字输入时,我只是简单地在
TextChanged事件上尝试Int32.TryParse或Double.TryParse。它使处理负号、小数或其他错误按键进行编辑(删除、复制/粘贴、箭头左/右键)的情况变得简单,然后只显示“请插入数字”的一般错误。 -
如果您在属性中使用ValidationException 绑定到您的
Textbox.Text属性,则文本框会自动设置红色边框和消息。见Silverlight validation。
标签: c# silverlight textbox