限制TextBox输入,只能输入整数

     public class TextBoxInt : TextBox
{
public TextBoxInt()
{
KeyDown += TextBoxInt_KeyDown;
TextChanged += TextBoxInt_TextChanged;
} private void TextBoxInt_TextChanged(object sender, TextChangedEventArgs e)
{
//屏蔽非法字符粘贴
var textBox = sender as TextBox;
if (textBox != null)
{
var change = new TextChange[e.Changes.Count];
e.Changes.CopyTo(change, ); int offset = change[].Offset;
if (change[].AddedLength > )
{
int num;
if (!int.TryParse(textBox.Text, out num))
{
textBox.Text = textBox.Text.Remove(offset, change[].AddedLength);
textBox.Select(offset, );
}
}
}
} private void TextBoxInt_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9)
{
// 允许输入数字小键盘上的数字0-9
e.Handled = false;
}
else if ((e.Key >= Key.D0 && e.Key <= Key.D9) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
{
// 允许输入数字0-9,并且不能同时按着Shift键
e.Handled = false;
}
else if (e.Key == Key.Enter)
{
// 允许输入回车
e.Handled = false;
}
else
{
e.Handled = true;
}
}
}
上一篇:高效测试用例组织算法pairwise之Python实现


下一篇:Kubernetes 笔记 03 扫清概念