WPF TextBox 限制只能输入正浮点数或正整数

原文: WPF TextBox 限制只能输入正浮点数或正整数

第一步:

TextBox添加PreviewTextInput事件,如下:

正浮点数用下面方法:


  
  
  1. //正浮点数
  2. private void tbTest_PreviewTextInput(object sender,TextCompositionEventArgs e)
  3. {
  4. //匹配只能输入一个小数点的浮点数
  5. Regex numbeRegex = new Regex( "^[.][0-9]+$|^[0-9]*[.]{0,1}[0-9]*$");
  6. e.Handled =
  7. !numbeRegex.IsMatch(
  8. tbTest.Text.Insert(
  9. tbTest.SelectionStart, e.Text));
  10. tbTest.Text = tbTest.Text.Trim();
  11. }

 正整数用下面方法:


  
  
  1. //正整数
  2. private void tbTest_PreviewTextInput(object sender,TextCompositionEventArgs e)
  3. {
  4. Regex re = new Regex( "[^0-9.-]+");
  5. e.Handled = re.IsMatch(e.Text);
  6. }

第二步:

禁用文本框中输入法如下:

<TextBox Name="tb_Test" InputMethod.IsInputMethodEnabled="False"/>
 
 

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12437385.html