WPF - MVVM Textbox restrict to specific characters

后端 未结 4 981
有刺的猬
有刺的猬 2021-01-14 01:42

I am trying to make text box accept only specific characters.

My TextBox is bound to the following:

    private string _CompanyID;
    public string          


        
4条回答
  •  心在旅途
    2021-01-14 02:07

    I do this with the PreviewtextInput event. I have a generic event used for multiple TextBoxes which takes the regex from a configuration table, but I have hard-coded the regex in this example.

    private void GenericTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
       e.Handled = !IsTextAllowed(e.Text, @"[^a-zA-Z]");
    }
    
    private static bool IsTextAllowed(string Text, string AllowedRegex)
    {
        try
        {
            var regex = new Regex(AllowedRegex);
            return !regex.IsMatch(Text);
        }
        catch
        {
            return true;
        }
    }
    

提交回复
热议问题