How do I get a TextBox to only accept numeric input in WPF?

后端 未结 30 2977
悲哀的现实
悲哀的现实 2020-11-22 03:40

I\'m looking to accept digits and the decimal point, but no sign.

I\'ve looked at samples using the NumericUpDown control for Windows Forms, and this sample of a Num

30条回答
  •  猫巷女王i
    2020-11-22 04:22

    After using some of the solutions here for some time, I developed my own that works well for my MVVM setup. Note that it's not as dynamic as some of the other ones in a sense of still allowing users to enter erroneous characters, but it blocks them from pressing the button and thus doing anything. This goes well with my theme of graying out buttons when actions cannot be performed.

    I have a TextBox that a user must enter a number of document pages to be printed:

    
    

    ...with this binding property:

    private string _numberPagesToPrint;
    public string NumberPagesToPrint
    {
        get { return _numberPagesToPrint; }
        set
        {
            if (_numberPagesToPrint == value)
            {
                return;
            }
    
            _numberPagesToPrint = value;
            OnPropertyChanged("NumberPagesToPrint");
        }
    }
    

    I also have a button:

    ...with this command binding:

    private RelayCommand _setNumberPagesCommand;
    public ICommand SetNumberPagesCommand
    {
        get
        {
            if (_setNumberPagesCommand == null)
            {
                int num;
                _setNumberPagesCommand = new RelayCommand(param => SetNumberOfPages(),
                    () => Int32.TryParse(NumberPagesToPrint, out num));
            }
    
            return _setNumberPagesCommand;
        }
    }
    

    And then there's the method of SetNumberOfPages(), but it's unimportant for this topic. It works well in my case because I don't have to add any code into the View's code-behind file and it allows me to control behavior using the Command property.

提交回复
热议问题