WPF - MVVM Textbox restrict to specific characters

后端 未结 4 953
有刺的猬
有刺的猬 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:00

    You should use a custom UI element there that restricts the input on the view-side using “classic” solutions like change listeners.

    For example, you can just create a simple subtype of TextBox that overrides the OnPreviewTextInput method. There, you can decide when some input should go through, or when you want to prevent it.

    For example, this is a custom TextBox that takes only characters from the ASCII alphabet:

    public class AlphabetTextBox : TextBox
    {
        private static readonly Regex regex = new Regex("^[a-zA-Z]+$");
    
        protected override void OnPreviewTextInput(TextCompositionEventArgs e)
        {
            if (!regex.IsMatch(e.Text))
                e.Handled = true;
            base.OnPreviewTextInput(e);
        }
    }
    

    Of course, you could also make the regular expression a property of the text box and allow people to set it from XAML. That way, you would get a very reusable component which you can use for various applications.

提交回复
热议问题