对于文本框的输入,不同的情况有个不同的需求。比如只能输入汉字,只能输入数字等。下面是一个只允许输入数字的方法,该方法在文本框的KeyDown事件触发。
private void CornerNumberTextBox_KeyDown(object sender, KeyEventArgs e) { TextBox txt = sender as TextBox; if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal) { if (txt.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.KeyboardDevice.Modifiers != ModifierKeys.Shift) { if (txt.Text.Contains(".") && e.Key == Key.OemPeriod) { e.Handled = true; return; } e.Handled = false; } else { e.Handled = true; } }