在使用中,我们经常遇到文本框中只允许输入数字(整型数或浮点数...) 的情况,如果我们输入特殊字符(字母和符号...),在获取其输入值时,如果先做判断或其他处理,会直接导致application发生crash。

那么开发限制性输入文本框的需求就应运而生。已经有了很多现成的尝试:

(1)https://www.codeproject.com/Articles/34228/WPF-Maskable-TextBox-for-Numeric-Values

This article describes how to enhance the WPF TextBox and make it accept just numeric (integer and floating point) values. The second goal is make the TextBox smart enough to make it easier to input numerics. This is an easy means to provide the TextBox with some kind of intelligence, not just rejecting non-numeric symbols. The provided extension also allows setting minimum and/or maximum values.

If you search in the net, you will probably find some solutions for this problem where developers create their own versions of the TextBox either by inheriting from it or creating a Custom/User Controls that include the standard WPF TextBox. Most other solutions have one major drawback - you would need to replace your TextBoxdefinitions with your new MaskTextBox. Sometimes, it is not painful, sometimes, it is. The reason I chose another solution is that in my case, such kind of changes would be painful.

The approach I’m proposing here is the usage of WPF Attached Properties, which basically are similar to Dependency Properties. The major difference among these to is that Dependency Properties are defined inside the control, but Attached Properties are defined outside. For instance, TextBox.Text is a Dependency Property, but Grid.Column is an Attached Property.

关键代码TextBoxMaskBehavior.cs:

  1. using System;
  2. using System.Windows;
  3. using System.Windows.Controls;
  4. using System.Globalization;
  5.  
  6. namespace Rubenhak.Common.WPF
  7. {
  8. #region Documentation Tags
  9. /// <summary>
  10. /// WPF Maskable TextBox class. Just specify the TextBoxMaskBehavior.Mask attached property to a TextBox.
  11. /// It protect your TextBox from unwanted non numeric symbols and make it easy to modify your numbers.
  12. /// </summary>
  13. /// <remarks>
  14. /// <para>
  15. /// Class Information:
  16. /// <list type="bullet">
  17. /// <item name="authors">Authors: Ruben Hakopian</item>
  18. /// <item name="date">February 2009</item>
  19. /// <item name="originalURL">http://www.rubenhak.com/?p=8</item>
  20. /// </list>
  21. /// </para>
  22. /// </remarks>
  23. #endregion
  24. public class TextBoxMaskBehavior
  25. {
  26. #region MinimumValue Property
  27.  
  28. public static double GetMinimumValue(DependencyObject obj)
  29. {
  30. return (double)obj.GetValue(MinimumValueProperty);
  31. }
  32.  
  33. public static void SetMinimumValue(DependencyObject obj, double value)
  34. {
  35. obj.SetValue(MinimumValueProperty, value);
  36. }
  37.  
  38. public static readonly DependencyProperty MinimumValueProperty =
  39. DependencyProperty.RegisterAttached(
  40. "MinimumValue",
  41. typeof(double),
  42. typeof(TextBoxMaskBehavior),
  43. new FrameworkPropertyMetadata(double.NaN, MinimumValueChangedCallback)
  44. );
  45.  
  46. private static void MinimumValueChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
  47. {
  48. TextBox _this = (d as TextBox);
  49. ValidateTextBox(_this);
  50. }
  51. #endregion
  52.  
  53. #region MaximumValue Property
  54.  
  55. public static double GetMaximumValue(DependencyObject obj)
  56. {
  57. return (double)obj.GetValue(MaximumValueProperty);
  58. }
  59.  
  60. public static void SetMaximumValue(DependencyObject obj, double value)
  61. {
  62. obj.SetValue(MaximumValueProperty, value);
  63. }
  64.  
  65. public static readonly DependencyProperty MaximumValueProperty =
  66. DependencyProperty.RegisterAttached(
  67. "MaximumValue",
  68. typeof(double),
  69. typeof(TextBoxMaskBehavior),
  70. new FrameworkPropertyMetadata(double.NaN, MaximumValueChangedCallback)
  71. );
  72.  
  73. private static void MaximumValueChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
  74. {
  75. TextBox _this = (d as TextBox);
  76. ValidateTextBox(_this);
  77. }
  78. #endregion
  79.  
  80. #region Mask Property
  81.  
  82. public static MaskType GetMask(DependencyObject obj)
  83. {
  84. return (MaskType)obj.GetValue(MaskProperty);
  85. }
  86.  
  87. public static void SetMask(DependencyObject obj, MaskType value)
  88. {
  89. obj.SetValue(MaskProperty, value);
  90. }
  91.  
  92. public static readonly DependencyProperty MaskProperty =
  93. DependencyProperty.RegisterAttached(
  94. "Mask",
  95. typeof(MaskType),
  96. typeof(TextBoxMaskBehavior),
  97. new FrameworkPropertyMetadata(MaskChangedCallback)
  98. );
  99.  
  100. private static void MaskChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
  101. {
  102. if (e.OldValue is TextBox)
  103. {
  104. (e.OldValue as TextBox).PreviewTextInput -= TextBox_PreviewTextInput;
  105. DataObject.RemovePastingHandler((e.OldValue as TextBox), (DataObjectPastingEventHandler)TextBoxPastingEventHandler);
  106. }
  107.  
  108. TextBox _this = (d as TextBox);
  109. if (_this == null)
  110. return;
  111.  
  112. if ((MaskType)e.NewValue != MaskType.Any)
  113. {
  114. _this.PreviewTextInput += TextBox_PreviewTextInput;
  115. DataObject.AddPastingHandler(_this, (DataObjectPastingEventHandler)TextBoxPastingEventHandler);
  116. }
  117.  
  118. ValidateTextBox(_this);
  119. }
  120.  
  121. #endregion
  122.  
  123. #region Private Static Methods
  124.  
  125. private static void ValidateTextBox(TextBox _this)
  126. {
  127. if (GetMask(_this) != MaskType.Any)
  128. {
  129. _this.Text = ValidateValue(GetMask(_this), _this.Text, GetMinimumValue(_this), GetMaximumValue(_this));
  130. }
  131. }
  132.  
  133. private static void TextBoxPastingEventHandler(object sender, DataObjectPastingEventArgs e)
  134. {
  135. TextBox _this = (sender as TextBox);
  136. string clipboard = e.DataObject.GetData(typeof(string)) as string;
  137. clipboard = ValidateValue(GetMask(_this), clipboard, GetMinimumValue(_this), GetMaximumValue(_this));
  138. if (!string.IsNullOrEmpty(clipboard))
  139. {
  140. _this.Text = clipboard;
  141. }
  142. e.CancelCommand();
  143. e.Handled = true;
  144. }
  145.  
  146. private static void TextBox_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
  147. {
  148. TextBox _this = (sender as TextBox);
  149. bool isValid = IsSymbolValid(GetMask(_this), e.Text);
  150. e.Handled = !isValid;
  151. if (isValid)
  152. {
  153. int caret = _this.CaretIndex;
  154. string text = _this.Text;
  155. bool textInserted = false;
  156. int selectionLength = 0;
  157.  
  158. if (_this.SelectionLength > 0)
  159. {
  160. text = text.Substring(0, _this.SelectionStart) +
  161. text.Substring(_this.SelectionStart + _this.SelectionLength);
  162. caret = _this.SelectionStart;
  163. }
  164.  
  165. if (e.Text == NumberFormatInfo.CurrentInfo.NumberDecimalSeparator)
  166. {
  167. while (true)
  168. {
  169. int ind = text.IndexOf(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator);
  170. if (ind == -1)
  171. break;
  172.  
  173. text = text.Substring(0, ind) + text.Substring(ind + 1);
  174. if (caret > ind)
  175. caret--;
  176. }
  177.  
  178. if (caret == 0)
  179. {
  180. text = "0" + text;
  181. caret++;
  182. }
  183. else
  184. {
  185. if (caret == 1 && string.Empty + text[0] == NumberFormatInfo.CurrentInfo.NegativeSign)
  186. {
  187. text = NumberFormatInfo.CurrentInfo.NegativeSign + "0" + text.Substring(1);
  188. caret++;
  189. }
  190. }
  191.  
  192. if (caret == text.Length)
  193. {
  194. selectionLength = 1;
  195. textInserted = true;
  196. text = text + NumberFormatInfo.CurrentInfo.NumberDecimalSeparator + "0";
  197. caret++;
  198. }
  199. }
  200. else if (e.Text == NumberFormatInfo.CurrentInfo.NegativeSign)
  201. {
  202. textInserted = true;
  203. if (_this.Text.Contains(NumberFormatInfo.CurrentInfo.NegativeSign))
  204. {
  205. text = text.Replace(NumberFormatInfo.CurrentInfo.NegativeSign, string.Empty);
  206. if (caret != 0)
  207. caret--;
  208. }
  209. else
  210. {
  211. text = NumberFormatInfo.CurrentInfo.NegativeSign + _this.Text;
  212. caret++;
  213. }
  214. }
  215.  
  216. if (!textInserted)
  217. {
  218. text = text.Substring(0, caret) + e.Text +
  219. ((caret < _this.Text.Length) ? text.Substring(caret) : string.Empty);
  220.  
  221. caret++;
  222. }
  223.  
  224. try
  225. {
  226. double val = Convert.ToDouble(text);
  227. double newVal = ValidateLimits(GetMinimumValue(_this), GetMaximumValue(_this), val);
  228. if (val != newVal)
  229. {
  230. text = newVal.ToString();
  231. }
  232. else if (val == 0)
  233. {
  234. if (!text.Contains(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator))
  235. text = "0";
  236. }
  237. }
  238. catch
  239. {
  240. text = "0";
  241. }
  242.  
  243. while (text.Length > 1 && text[0] == '0' && string.Empty + text[1] != NumberFormatInfo.CurrentInfo.NumberDecimalSeparator)
  244. {
  245. text = text.Substring(1);
  246. if (caret > 0)
  247. caret--;
  248. }
  249.  
  250. while (text.Length > 2 && string.Empty + text[0] == NumberFormatInfo.CurrentInfo.NegativeSign && text[1] == '0' && string.Empty + text[2] != NumberFormatInfo.CurrentInfo.NumberDecimalSeparator)
  251. {
  252. text = NumberFormatInfo.CurrentInfo.NegativeSign + text.Substring(2);
  253. if (caret > 1)
  254. caret--;
  255. }
  256.  
  257. if (caret > text.Length)
  258. caret = text.Length;
  259.  
  260. _this.Text = text;
  261. _this.CaretIndex = caret;
  262. _this.SelectionStart = caret;
  263. _this.SelectionLength = selectionLength;
  264. e.Handled = true;
  265. }
  266. }
  267.  
  268. private static string ValidateValue(MaskType mask, string value, double min, double max)
  269. {
  270. if (string.IsNullOrEmpty(value))
  271. return string.Empty;
  272.  
  273. value = value.Trim();
  274. switch (mask)
  275. {
  276. case MaskType.Integer:
  277. try
  278. {
  279. Convert.ToInt64(value);
  280. return value;
  281. }
  282. catch
  283. {
  284. }
  285. return string.Empty;
  286.  
  287. case MaskType.Decimal:
  288. try
  289. {
  290. Convert.ToDouble(value);
  291.  
  292. return value;
  293. }
  294. catch
  295. {
  296. }
  297. return string.Empty;
  298. }
  299.  
  300. return value;
  301. }
  302.  
  303. private static double ValidateLimits(double min, double max, double value)
  304. {
  305. if (!min.Equals(double.NaN))
  306. {
  307. if (value < min)
  308. return min;
  309. }
  310.  
  311. if (!max.Equals(double.NaN))
  312. {
  313. if (value > max)
  314. return max;
  315. }
  316.  
  317. return value;
  318. }
  319.  
  320. private static bool IsSymbolValid(MaskType mask, string str)
  321. {
  322. switch (mask)
  323. {
  324. case MaskType.Any:
  325. return true;
  326.  
  327. case MaskType.Integer:
  328. if (str == NumberFormatInfo.CurrentInfo.NegativeSign)
  329. return true;
  330. break;
  331.  
  332. case MaskType.Decimal:
  333. if (str == NumberFormatInfo.CurrentInfo.NumberDecimalSeparator ||
  334. str == NumberFormatInfo.CurrentInfo.NegativeSign)
  335. return true;
  336. break;
  337. }
  338.  
  339. if (mask.Equals(MaskType.Integer) || mask.Equals(MaskType.Decimal))
  340. {
  341. foreach (char ch in str)
  342. {
  343. if (!Char.IsDigit(ch))
  344. return false;
  345. }
  346.  
  347. return true;
  348. }
  349.  
  350. return false;
  351. }
  352.  
  353. #endregion
  354. }
  355.  
  356. public enum MaskType
  357. {
  358. Any,
  359. Integer,
  360. Decimal
  361. }
  362. }

  

(2)Simple Numeric TextBox : https://www.codeproject.com/Articles/30812/Simple-Numeric-TextBox

这是System.Windows.Forms.TextBox组件的简单扩展/限制。 只有数字可以输入控件。 粘贴也被检查,如果文本包含其他字符,则被取消。

最后我的解决方案:

对文本框中输入的字符进行类型判断(是否为整数或浮点数等),然后对输入非法字符的情况进行错误提示。 ps:允许在输入中,带有空格。使用trim函数过滤前后空格。

因为如果从源头处限制非法字符的输入,存在以下弊端:

(1)检查的情况多,从键盘上不允许输入其他非法字符。

(2)在上面第一种方法中,发现仍然存在漏洞,当切换为中文输入法后,键入非法字符然后enter,这样也能输入非法字符。

(3)需要考虑复制粘贴时引入的非法字符(1.ctrl + C 2.鼠标 复制)

C# Note12:WPF只允许数字的限制性TextBox的更多相关文章

  1. PHP 向 MySql 中数据修改操作时,只对数字操作有效,非数字操作无效,怎么办?

    问题描述:   用PHP向MySql数据库中修改数据,实现增删改(数据库能正确连接) 经测试,代码只能对数字进行正常的增删改操作,非数字操作无效   但要在课程名称中输入中文,应该如果修改呢?   存 ...

  2. wpf只运行一个实例

    原文:wpf只运行一个实例 在winform下,只运行一个实例只需这样就可以: 1. 首先要添加如下的namespace: using System.Threading; 2. 修改系统Main函数, ...

  3. 【Teradata SQL】从中文数字字母混合字符串中只提取数字regexp_substr

    目标:从中文数字字母的字符串中只提取数字 sel regexp_substr('mint choc中文11国1','\d+')

  4. C# 判断输入的字符串是否只包含数字和英文字母

    /// <summary> /// 判断输入的字符串是否只包含数字和英文字母 /// </summary> /// <param name="input&quo ...

  5. ASP.NET C# 登陆窗体 限制用户名只输入字母 数字以及下划线

    文本框的输入限制,我们主要集中两个问题: 一.怎样限制用户名输入的长度? 答:设置txtName的属性 MaxLength="; (我们这里以10个字符为例) 二.怎样限制用户名只输入字母 ...

  6. 文本框只支持数字、小数点、退格符、负号、Del键

    Public Function OnlyNumberAndDot(inKeyAscii As Integer) As Integer '函数说明:文本框只支持数字.小数点.退格符.负号.Del键 '入 ...

  7. android代码设置EditText只输入数字、字母

     如何设置EditText,使得只能输入数字或者某些字母呢? 一.设置EditText,只输入数字: 方法1:直接生成DigitsKeyListener对象就可以了. et_1.setKeyLis ...

  8. Python isdigit() 方法检测字符串是否只由数字组成

    Python isdigit() 方法检测字符串是否只由数字组成

  9. python3 之 判断字符串是否只为数字(isdigit()方法、isnumeric()方法)

    Isdigit()方法 - 检测字符串是否只由数字组成 语法:   str.isdigit() 参数: 无 返回值: 如果字符串只包含数字,则返回True,否则返回False. 实例: 以下实例展示了 ...

随机推荐

  1. php面试题整理(三)

    判断是不是ie浏览器 1,1

  2. KazaQ's Socks (找规律)

    #include<iostream> using namespace std; #define ll long long ll n, m; ll t; int main(){ while ...

  3. VS2015中配置Eigen

    Eigen非常方便矩阵操作,当然它的功能不止如此.矩阵操作在算法研究过程中,非常重要,例如在图像处理中二维高斯拟合求取光斑中心时使用Eigen提供的矩阵算法,差不多十来行代码即可实现. 1)下载Eig ...

  4. Spring Security(二十五):7. Sample Applications

    There are several sample web applications that are available with the project. To avoid an overly la ...

  5. vector--不定长数组

    (一些很基础的东西) vector就是一个不定长数组 vector<int>a (黄色部分可替换) a.size() 读取它的大小 a.resize() 改变大小 a.push_back( ...

  6. tomcat目录结构以及项目部署

    摘要:tomcat的目录结构 tomcat是一个轻量级的免费开源的web服务器,使用非常方便,也是最普遍的一款优秀服务器. 一.tomcat目录结构 1.官方下载  http://tomcat.apa ...

  7. 在Ubuntu上快速搭建基于Beego的RESTful API

    最近在研究Go,打算基于Go做点Web API,于是经过初步调研,打算用Beego这个框架,然后再结合其中提供的ORM以及Swagger的集成,可以快速搭建一个RESTful API的网站. 下面是具 ...

  8. Sqlserver内存管理:限制最大占用内存(转载)

    一.Sqlserver对系统内存的管理原则是:按需分配,且贪婪(用完不还).它不会自动释放内存,因此执行结果集大的sql语句时,数据取出后,会一直占用内存,直到占满机器内存(并不会撑满,还是有个最大限 ...

  9. linux驱动编写之poll机制

    一.概念 1.poll情景描述 以按键驱动为例进行说明,用阻塞的方式打开按键驱动文件/dev/buttons,应用程序使用read()函数来读取按键的键值.这样做的效果是:如果有按键按下了,调用该re ...

  10. UITextFieldDelegate 说明

    - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField  // 返回YES,允许进行编辑 - (void)textFieldDidBe ...