C# Note12:WPF只允许数字的限制性TextBox
在使用中,我们经常遇到文本框中只允许输入数字(整型数或浮点数...) 的情况,如果我们输入特殊字符(字母和符号...),在获取其输入值时,如果先做判断或其他处理,会直接导致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:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Globalization; namespace Rubenhak.Common.WPF
{
#region Documentation Tags
/// <summary>
/// WPF Maskable TextBox class. Just specify the TextBoxMaskBehavior.Mask attached property to a TextBox.
/// It protect your TextBox from unwanted non numeric symbols and make it easy to modify your numbers.
/// </summary>
/// <remarks>
/// <para>
/// Class Information:
/// <list type="bullet">
/// <item name="authors">Authors: Ruben Hakopian</item>
/// <item name="date">February 2009</item>
/// <item name="originalURL">http://www.rubenhak.com/?p=8</item>
/// </list>
/// </para>
/// </remarks>
#endregion
public class TextBoxMaskBehavior
{
#region MinimumValue Property public static double GetMinimumValue(DependencyObject obj)
{
return (double)obj.GetValue(MinimumValueProperty);
} public static void SetMinimumValue(DependencyObject obj, double value)
{
obj.SetValue(MinimumValueProperty, value);
} public static readonly DependencyProperty MinimumValueProperty =
DependencyProperty.RegisterAttached(
"MinimumValue",
typeof(double),
typeof(TextBoxMaskBehavior),
new FrameworkPropertyMetadata(double.NaN, MinimumValueChangedCallback)
); private static void MinimumValueChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextBox _this = (d as TextBox);
ValidateTextBox(_this);
}
#endregion #region MaximumValue Property public static double GetMaximumValue(DependencyObject obj)
{
return (double)obj.GetValue(MaximumValueProperty);
} public static void SetMaximumValue(DependencyObject obj, double value)
{
obj.SetValue(MaximumValueProperty, value);
} public static readonly DependencyProperty MaximumValueProperty =
DependencyProperty.RegisterAttached(
"MaximumValue",
typeof(double),
typeof(TextBoxMaskBehavior),
new FrameworkPropertyMetadata(double.NaN, MaximumValueChangedCallback)
); private static void MaximumValueChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextBox _this = (d as TextBox);
ValidateTextBox(_this);
}
#endregion #region Mask Property public static MaskType GetMask(DependencyObject obj)
{
return (MaskType)obj.GetValue(MaskProperty);
} public static void SetMask(DependencyObject obj, MaskType value)
{
obj.SetValue(MaskProperty, value);
} public static readonly DependencyProperty MaskProperty =
DependencyProperty.RegisterAttached(
"Mask",
typeof(MaskType),
typeof(TextBoxMaskBehavior),
new FrameworkPropertyMetadata(MaskChangedCallback)
); private static void MaskChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.OldValue is TextBox)
{
(e.OldValue as TextBox).PreviewTextInput -= TextBox_PreviewTextInput;
DataObject.RemovePastingHandler((e.OldValue as TextBox), (DataObjectPastingEventHandler)TextBoxPastingEventHandler);
} TextBox _this = (d as TextBox);
if (_this == null)
return; if ((MaskType)e.NewValue != MaskType.Any)
{
_this.PreviewTextInput += TextBox_PreviewTextInput;
DataObject.AddPastingHandler(_this, (DataObjectPastingEventHandler)TextBoxPastingEventHandler);
} ValidateTextBox(_this);
} #endregion #region Private Static Methods private static void ValidateTextBox(TextBox _this)
{
if (GetMask(_this) != MaskType.Any)
{
_this.Text = ValidateValue(GetMask(_this), _this.Text, GetMinimumValue(_this), GetMaximumValue(_this));
}
} private static void TextBoxPastingEventHandler(object sender, DataObjectPastingEventArgs e)
{
TextBox _this = (sender as TextBox);
string clipboard = e.DataObject.GetData(typeof(string)) as string;
clipboard = ValidateValue(GetMask(_this), clipboard, GetMinimumValue(_this), GetMaximumValue(_this));
if (!string.IsNullOrEmpty(clipboard))
{
_this.Text = clipboard;
}
e.CancelCommand();
e.Handled = true;
} private static void TextBox_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
{
TextBox _this = (sender as TextBox);
bool isValid = IsSymbolValid(GetMask(_this), e.Text);
e.Handled = !isValid;
if (isValid)
{
int caret = _this.CaretIndex;
string text = _this.Text;
bool textInserted = false;
int selectionLength = 0; if (_this.SelectionLength > 0)
{
text = text.Substring(0, _this.SelectionStart) +
text.Substring(_this.SelectionStart + _this.SelectionLength);
caret = _this.SelectionStart;
} if (e.Text == NumberFormatInfo.CurrentInfo.NumberDecimalSeparator)
{
while (true)
{
int ind = text.IndexOf(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator);
if (ind == -1)
break; text = text.Substring(0, ind) + text.Substring(ind + 1);
if (caret > ind)
caret--;
} if (caret == 0)
{
text = "0" + text;
caret++;
}
else
{
if (caret == 1 && string.Empty + text[0] == NumberFormatInfo.CurrentInfo.NegativeSign)
{
text = NumberFormatInfo.CurrentInfo.NegativeSign + "0" + text.Substring(1);
caret++;
}
} if (caret == text.Length)
{
selectionLength = 1;
textInserted = true;
text = text + NumberFormatInfo.CurrentInfo.NumberDecimalSeparator + "0";
caret++;
}
}
else if (e.Text == NumberFormatInfo.CurrentInfo.NegativeSign)
{
textInserted = true;
if (_this.Text.Contains(NumberFormatInfo.CurrentInfo.NegativeSign))
{
text = text.Replace(NumberFormatInfo.CurrentInfo.NegativeSign, string.Empty);
if (caret != 0)
caret--;
}
else
{
text = NumberFormatInfo.CurrentInfo.NegativeSign + _this.Text;
caret++;
}
} if (!textInserted)
{
text = text.Substring(0, caret) + e.Text +
((caret < _this.Text.Length) ? text.Substring(caret) : string.Empty); caret++;
} try
{
double val = Convert.ToDouble(text);
double newVal = ValidateLimits(GetMinimumValue(_this), GetMaximumValue(_this), val);
if (val != newVal)
{
text = newVal.ToString();
}
else if (val == 0)
{
if (!text.Contains(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator))
text = "0";
}
}
catch
{
text = "0";
} while (text.Length > 1 && text[0] == '0' && string.Empty + text[1] != NumberFormatInfo.CurrentInfo.NumberDecimalSeparator)
{
text = text.Substring(1);
if (caret > 0)
caret--;
} while (text.Length > 2 && string.Empty + text[0] == NumberFormatInfo.CurrentInfo.NegativeSign && text[1] == '0' && string.Empty + text[2] != NumberFormatInfo.CurrentInfo.NumberDecimalSeparator)
{
text = NumberFormatInfo.CurrentInfo.NegativeSign + text.Substring(2);
if (caret > 1)
caret--;
} if (caret > text.Length)
caret = text.Length; _this.Text = text;
_this.CaretIndex = caret;
_this.SelectionStart = caret;
_this.SelectionLength = selectionLength;
e.Handled = true;
}
} private static string ValidateValue(MaskType mask, string value, double min, double max)
{
if (string.IsNullOrEmpty(value))
return string.Empty; value = value.Trim();
switch (mask)
{
case MaskType.Integer:
try
{
Convert.ToInt64(value);
return value;
}
catch
{
}
return string.Empty; case MaskType.Decimal:
try
{
Convert.ToDouble(value); return value;
}
catch
{
}
return string.Empty;
} return value;
} private static double ValidateLimits(double min, double max, double value)
{
if (!min.Equals(double.NaN))
{
if (value < min)
return min;
} if (!max.Equals(double.NaN))
{
if (value > max)
return max;
} return value;
} private static bool IsSymbolValid(MaskType mask, string str)
{
switch (mask)
{
case MaskType.Any:
return true; case MaskType.Integer:
if (str == NumberFormatInfo.CurrentInfo.NegativeSign)
return true;
break; case MaskType.Decimal:
if (str == NumberFormatInfo.CurrentInfo.NumberDecimalSeparator ||
str == NumberFormatInfo.CurrentInfo.NegativeSign)
return true;
break;
} if (mask.Equals(MaskType.Integer) || mask.Equals(MaskType.Decimal))
{
foreach (char ch in str)
{
if (!Char.IsDigit(ch))
return false;
} return true;
} return false;
} #endregion
} public enum MaskType
{
Any,
Integer,
Decimal
}
}
(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的更多相关文章
- PHP 向 MySql 中数据修改操作时,只对数字操作有效,非数字操作无效,怎么办?
问题描述: 用PHP向MySql数据库中修改数据,实现增删改(数据库能正确连接) 经测试,代码只能对数字进行正常的增删改操作,非数字操作无效 但要在课程名称中输入中文,应该如果修改呢? 存 ...
- wpf只运行一个实例
原文:wpf只运行一个实例 在winform下,只运行一个实例只需这样就可以: 1. 首先要添加如下的namespace: using System.Threading; 2. 修改系统Main函数, ...
- 【Teradata SQL】从中文数字字母混合字符串中只提取数字regexp_substr
目标:从中文数字字母的字符串中只提取数字 sel regexp_substr('mint choc中文11国1','\d+')
- C# 判断输入的字符串是否只包含数字和英文字母
/// <summary> /// 判断输入的字符串是否只包含数字和英文字母 /// </summary> /// <param name="input&quo ...
- ASP.NET C# 登陆窗体 限制用户名只输入字母 数字以及下划线
文本框的输入限制,我们主要集中两个问题: 一.怎样限制用户名输入的长度? 答:设置txtName的属性 MaxLength="; (我们这里以10个字符为例) 二.怎样限制用户名只输入字母 ...
- 文本框只支持数字、小数点、退格符、负号、Del键
Public Function OnlyNumberAndDot(inKeyAscii As Integer) As Integer '函数说明:文本框只支持数字.小数点.退格符.负号.Del键 '入 ...
- android代码设置EditText只输入数字、字母
如何设置EditText,使得只能输入数字或者某些字母呢? 一.设置EditText,只输入数字: 方法1:直接生成DigitsKeyListener对象就可以了. et_1.setKeyLis ...
- Python isdigit() 方法检测字符串是否只由数字组成
Python isdigit() 方法检测字符串是否只由数字组成
- python3 之 判断字符串是否只为数字(isdigit()方法、isnumeric()方法)
Isdigit()方法 - 检测字符串是否只由数字组成 语法: str.isdigit() 参数: 无 返回值: 如果字符串只包含数字,则返回True,否则返回False. 实例: 以下实例展示了 ...
随机推荐
- 代理 IP 云打码平台的使用
代理ip 获取代理ip的网站: 快代理 西祠代理 www.goubanjia.com #代理ip import requests headers = { 'User-Agent':'Mozilla/5 ...
- WPF模板(一)详细介绍
本次随笔来源于电子书,人家的讲解很好,我就不画蛇添足了. 图形用户界面应用程序较之控制台界面应用程序最大的好处就是界面友好.数据显示直观.CUI程序中数据只能以文本的形式线性显示,GUI程序则允许数据 ...
- Web开发人员vs网页设计师
Web开发人员vs网页设计师 我们都遇到过,但实际的区别是什么?如果您是该领域的新手,请阅读详细内容,这些内容比您想象的更重要. 经过几周(或几个月)的规划和准备,进行市场调查,与其他企业家交谈,现在 ...
- access数据库查找以及如果结果中存在多个匹配用户该怎么处理?
查找用户的界面为: 首先对查找条件进行赋值: if (radioButton1.Checked) serMatchInfo = "用户姓名"; if (radioButton2.C ...
- -bash: _docker_machine_ps1: 未找到命令
场景:在安装完docker-machine,设置docker-machine命令自动补齐的时候,出现以下错误: -bash: __docker_machine_ps1: 未找到命令 解决办法:在~/. ...
- centos7下安装docker(17.4docker监控----prometheus)
Prometheus是一个非常优秀的监控工具.准确的说,应该是监控方案.Prometheus提供了监控数据搜集,存储,处理,可视化和告警一套完整的解决方案 Prometheus架构如盗图: 官网上的原 ...
- 小a的子序列 (线性dp)
思路:设dp[i][j]表示最大数为j,i为第i的位置的萌值.那么推导过程就是两种情况:1.第i位数不放数字,则结果就是dp[i-1][j]; 2.第i位放数字,则结果就是前面的萌值sum+dp[i- ...
- Echo团队Alpha冲刺随笔 - 第五天
项目冲刺情况 进展 前端:布局,内容等方面基本完成. 后端:基本功能基本实现. 计划:准备进行前后端对接,进行测试 问题 有部分代码冗余,需要着手修改 心得 团队分工明确,互相协作,开发进度比预想的要 ...
- ExFilePicker的使用 — 获取本地图片资源并用RecyclerView展示出来
代码其实很简单,所以就不多进行文字说明,直接上完整的代码: 第一步:在app/build.gradle添加需要使用到的依赖库:(这里对引用的版本冲突问题作了处理,详情请看链接:https://www. ...
- Fiddler抓包和修改WebSocket数据,支持wss
记录一下用Fiddler对WebSocket收发的数据进行抓包分析和篡改数据,只找到这么一个方法,能用就行吧. 时间:2019-3-29 环境: win7 + Fiddler 5.0 Fiddler抓 ...