wpf 屏蔽文本框以仅接受小数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12209484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Masking Textbox to accept only decimals
提问by l46kok
I am using the technique from this link to mask my textbox to accept strings that are in decimal-format (Digits with a single period).
我正在使用此链接中的技术来屏蔽我的文本框以接受十进制格式的字符串(带有单个句点的数字)。
How to define TextBox input restrictions?
Here is the regex I put in the mask:
这是我放在掩码中的正则表达式:
b:Masking.Mask="^\d+(\.\d{1,2})?$"
For some odd reason, it lets me input the digits but I cannot insert the period in my textbox.
出于某种奇怪的原因,它让我输入数字,但我无法在我的文本框中插入句点。
I've also validated the regex here so regex is definitely correct.
我也在这里验证了正则表达式,所以正则表达式绝对是正确的。
http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx
http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx
What could be the issue?
可能是什么问题?
回答by Vishal Suthar
回答by andy
Either you can use the Regular Expression
您可以使用正则表达式
^(\d+)?+([\.]{1})?+([\d]{1,2})?$
Or you can use below event
或者您可以使用以下事件
bool blHasDot = false;
private void txt_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsDigit(e.KeyChar) || e.KeyChar == '\b')
{
// Allow Digits and BackSpace char
}
else if (e.KeyChar == '.' && !blHasDot)
{
//Allows only one Dot Char
blHasDot=true;
}
else
{
e.Handled = true;
}
}

