只能输入数字和并保留两位小数点
private void txt_PreviewTextInput(object sender, TextCompositionEventArgs e) { Regex re = new Regex("[^0-9.-]+"); e.Handled = re.IsMatch(e.Text); var textBox = e.OriginalSource as TextBox; if (textBox != null) { if (!string.IsNullOrWhiteSpace(textBox.Text)) { if (textBox.Text.Substring(textBox.Text.Length - 1) != ".") { if (!textBox.Text.Contains(".")) { textBox.MaxLength = 10;//长度为10 } if (decimal.TryParse(textBox.Text, out var anyAmount)) { // Text成功转为deciml后逻辑 } } else { textBox.MaxLength = textBox.Text.Length + 2; } } else { // Text为空逻辑 } } }
只能输入英文
private void txt_PreviewTextInput(object sender, TextCompositionEventArgs e) { Regex re = new Regex("^[A−Za−z]+"); e.Handled = re.IsMatch(e.Text); Regex reNUmber = new Regex("[^0-9]+"); e.Handled = !reNUmber.IsMatch(e.Text); }
只能输入英文和数字
private void txr_PreviewTextInput(object sender, TextCompositionEventArgs e) { Regex re = new Regex("^[A−Za−z0−9]+"); if (!e.Text.Equals("0")) { e.Handled = re.IsMatch(e.Text); } }
禁用键盘粘贴
private void txt_PreviewKeyDown(object sender, KeyEventArgs e) { if ((e.KeyStates == Keyboard.GetKeyStates(Key.LeftCtrl) || e.KeyStates == Keyboard.GetKeyStates(Key.RightCtrl)) && e.KeyStates == Keyboard.GetKeyStates(Key.V)) { e.Handled = true; } else { e.Handled = false; } }