本文主要是介绍WPF TextBox 只能输入数字,并限制输入大小,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/// <summary>/// 文本框文本输入事件/// </summary>private void txt_PreviewTextInput(object sender, TextCompositionEventArgs e){Regex regex = new Regex("^[0-9]+$");e.Handled = !regex.IsMatch(e.Text);if (e.Handled)return;try{TextBox txtBox = sender as TextBox;string strTag = txtBox.Tag.ToString().Replace("Seconds", "").Replace("ms", "").Replace("s", "").Replace("d", "").Replace("%", "").Replace("(", "").Replace(")", "").Replace("(", "").Replace(")", "");string strText = txtBox.Text + e.Text;int max = 0;int min = 0;if (!string.IsNullOrWhiteSpace(strTag)){string[] strs = strTag.Split('-');max = min = int.Parse(strs[0]);foreach (string str in strs){int num = int.Parse(str);if (num < min)min = num;if (num > max)max = num;}}int number = int.Parse(strText);if (number >= min && number <= max)e.Handled = false;elsee.Handled = true;}catch (Exception ex){e.Handled = true;}}/// <summary>/// 键盘按键事件/// 禁用粘贴/// </summary>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;elsee.Handled = false;}
<TextBox Name="txt" Text="3" Tag=" s ( 0 - 20 s )" IsEnabled="False" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120" Height="25" Margin="5,20,0,0" Style="{DynamicResource txtBoxStyle}"input:InputMethod.IsInputMethodEnabled="False" PreviewTextInput="txt_PreviewTextInput" PreviewKeyDown="txt_PreviewKeyDown"/>
这篇关于WPF TextBox 只能输入数字,并限制输入大小的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!