2015-12-08 104 views

回答

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); 
} 
相关问题