最近做项目用到了只能输入数字的TextBox控件,于是自己百度了一下,最终总结如下:
</pre><pre name="code" class="csharp"> protected override void OnPreviewKeyDown(KeyEventArgs e)
{
if (this.IsOnlyNumber)
{
// 屏蔽非法按键
if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal || e.Key == Key.Back)
{
if (this.Text.Contains(".") && e.Key == Key.Decimal)
{
e.Handled = true;
return;
}
e.Handled = false;
}
else if (((e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod || e.Key == Key.Back) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
{
if (this.Text.Contains(".") && e.Key == Key.OemPeriod)
{
e.Handled = true;
return;
}
e.Handled = false;
}
else
{
e.Handled = true;
}
}
base.OnPreviewKeyDown(e);
}
protected override void OnPreviewTextInput(TextCompositionEventArgs e)
{
if (this.IsOnlyNumber)
{
if (!this.isNumberic(e.Text))
{
e.Handled = true;
}
else
{
e.Handled = false;
}
}
base.OnPreviewTextInput(e);
}
private bool isNumberic(string _string)
{
if (string.IsNullOrEmpty(_string))
{
return false;
}
foreach (char c in _string)
{
if (!char.IsDigit(c))
{
return false;
}
}
return true;
}
上述方法不能排除输入中文,因此又在网上搜了一下,禁用了输入法,方法如下:
在使用TextBox的界面先引用
xmlns:input="clr-namespace:System.Windows.Input;assembly=PresentationCore"
然后在TextBox控件中增加属性
input:InputMethod.IsInputMethodEnabled="False"
至此搞定。。。。