WPF TextBox設置輸入限制 用正則表達式方式


只能輸入數字的限制

在XAML文件里

<TextBox PreviewTextInput=
"TextBox_PreviewTextInput"></TextBox>

xaml.cs文件里

private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    Regex re = new Regex("[^0-9.-]+");

    e.Handled = re.IsMatch(e.Text);
}

以上這種方式是以相反的方式來設置正則表達式,該正則表達式是不為數字的意思

只能輸入正整數和0

xaml.cs文件里

private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    Regex re = new Regex("^[1-9]+[0-9]*$");

    e.Handled = !re.IsMatch(e.Text);
}

以上這種方式是以正向的方式來設置正則表達式,但后面的match就應該取反

不能輸入漢字

在xaml文件


 xmlns:input="clr-namespace:System.Windows.Input;assembly=PresentationCore"


<TextBox input:InputMethod.IsInputMethodEnabled="False"></TextBox>

這種方式限制輸入法使用,就只能輸入英文,數字,字符等,不能輸入漢字


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM