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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 05:10:33  来源:igfitidea点击:

Masking Textbox to accept only decimals

c#.netwpfregexmaskedtextbox

提问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?

如何定义TextBox输入限制?

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

Modify your regex with this:

用这个修改你的正则表达式:

^\d+([\.\d].{1,2})?$

DEMO

演示

EDIT:

编辑:

The above regex will also allow 123..1that is more than 1 decimal point. so I just found the problem and fixed with the below one:

上面的正则表达式也允许123..1超过 1 个小数点。所以我刚刚发现了问题并使用以下方法进行了修复:

^(\d+)?+([\.]{1})?+([\d]{1,2})?$

DEMO

演示

回答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;
        }
    }