首页 > Windows开发 > 详细

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

时间:2020-03-07 22:06:33      阅读:315      评论:0      收藏:0      [点我收藏+]
原文: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"/>

 

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

原文:https://www.cnblogs.com/lonelyxmas/p/12437385.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!