将文本框输入限制为C#中的数字和点(。)

时间:2015-12-08 19:05:23

标签: c#

我想限制文本框接受1到4之间的数字,并且在C#中也包含点(。)。我该怎么做?

2 个答案:

答案 0 :(得分:0)

您可以将KeyPress事件绑定到文本框,然后使用regex添加验证,如下所述:How to block or restrict special characters from textbox

答案 1 :(得分:0)

您可以在软件中使用以下代码段。该属性完全由代码隐藏处理,您可以将其作为文本框属性附加在XAML部分中。

PreviewTextInput正在按键上检查输入字符,因此不允许无效字符。在正则表达式中,定义了允许的字符。

XAML部分:     

部分背后的代码

...
NumberRestrictFunction();
...

public void NumberRestrictFunction()
{
    textBox.PreviewTextInput += new TextCompositionEventHandler(MyNumbers_PreviewTextInput);
}

public static void MyNumbers_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    e.Handled = CheckIfMyCharacters(e.Text);
}

public static bool CheckIfMyCharacters(String text)
{
    Regex regex = new Regex(@"[1-4.]+");  
    return !regex.IsMatch(text);
}