WPF - MVVM Textbox restrict to specific characters

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

    The problem is, humans type in numbers sequentially, the fools.
    To type in "0.1", a legitimate string, you have to type in "0.", which fails. Also, re the accepted answer from @poke (which is great), the e.Text value is the change to the textbox (keystroke).
    You must add this change to the current textbox string, and then validate the concatenated candidate string, and see if that is valid. Humans are also wiley, so they will paste from the clipboard to get around the restriction.
    With a textbox, you will never be able to block all garbage in, because at some point the user will have to go through garbage, to get to a valid string.
    So you can block illegal character entry using e.Text, or allow sequential step failure. But you will still have to check the final string for validity too.
    Below is an example of a textbox that allows users to type in a decimal value with a max of 8 dec places in, but they could still cheat this by pasting from the clipboard.

    ////////////////////////
    // REGEXTEXTBOX CLASS //
    ////////////////////////
    
    
    using System.Windows.Controls; // Textbox
    using System.Windows.Input;
    using System.Text.RegularExpressions; // Regex
    
    namespace MyNamespace
    {
        public class RegexTextBox : TextBox
        {
            private Regex _regex = null;
    
            public Regex Regex
            {
                get { return _regex; }
                set { _regex = value; }
            }
    
    
            ///////////////////////////////////////////////////////////////////////
            // MEMBERS
    
            protected override void OnPreviewTextInput(TextCompositionEventArgs e)
            {
                var prefix = "OnPreviewTextInput() - ";
                logger.Debug(prefix + "Entering");
    
                string currentText = this.Text;
                string candidateText = currentText + e.Text;
    
                // If we have a set regex, and the current text fails,
                // mark as handled so the text is not processed.
                if (_regex != null && !_regex.IsMatch(candidateText))
                {
                    e.Handled = true;
                }           
    
                base.OnPreviewTextInput(e);
            }
    
        } // end of class RegexTextbox
    
    } // end of MyNamespace
    
    
    /////////////////////
    // MAINWINDOW.XAML //
    /////////////////////
    
    //(Window class needs to know your namespace so it needs xmlns:myNamespace="clr-namespace:MyNamespace")
    
    
     
    
    
    ////////////////////////
    // MAINWINDOW.XAML.CS //
    ////////////////////////
    
    namespace MyNamespace
    {
        /// 
        /// Interaction logic for MainWindow.xaml
        /// 
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
    
                textboxPayToAmount.Regex = 
                    new System.Text.RegularExpressions.Regex(@"^\d*(\.\d{0,8})?$");
            }
        }
    }
    

提交回复
热议问题