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

后端 未结 30 2291
悲哀的现实
悲哀的现实 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条回答
  • PreviewTextInput += (s, e) =>
    {
        e.Handled = !e.Text.All(char.IsDigit);
    };
    
    0 讨论(0)
  • 2020-11-22 04:19

    Here is my version of it. It's based on a base ValidatingTextBox class that just undoes what has been done if it's not "valid". It supports paste, cut, delete, backspace, +, - etc.

    For 32-bit integer, there is a Int32TextBox class that just compares with an int. I have also added floating point validation classes.

    public class ValidatingTextBox : TextBox
    {
        private bool _inEvents;
        private string _textBefore;
        private int _selectionStart;
        private int _selectionLength;
    
        public event EventHandler<ValidateTextEventArgs> ValidateText;
    
        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            if (_inEvents)
                return;
    
            _selectionStart = SelectionStart;
            _selectionLength = SelectionLength;
            _textBefore = Text;
        }
    
        protected override void OnTextChanged(TextChangedEventArgs e)
        {
            if (_inEvents)
                return;
    
            _inEvents = true;
            var ev = new ValidateTextEventArgs(Text);
            OnValidateText(this, ev);
            if (ev.Cancel)
            {
                Text = _textBefore;
                SelectionStart = _selectionStart;
                SelectionLength = _selectionLength;
            }
            _inEvents = false;
        }
    
        protected virtual void OnValidateText(object sender, ValidateTextEventArgs e) => ValidateText?.Invoke(this, e);
    }
    
    public class ValidateTextEventArgs : CancelEventArgs
    {
        public ValidateTextEventArgs(string text) => Text = text;
    
        public string Text { get; }
    }
    
    public class Int32TextBox : ValidatingTextBox
    {
        protected override void OnValidateText(object sender, ValidateTextEventArgs e) => e.Cancel = !int.TryParse(e.Text, out var value);
    }
    
    public class Int64TextBox : ValidatingTextBox
    {
        protected override void OnValidateText(object sender, ValidateTextEventArgs e) => e.Cancel = !long.TryParse(e.Text, out var value);
    }
    
    public class DoubleTextBox : ValidatingTextBox
    {
        protected override void OnValidateText(object sender, ValidateTextEventArgs e) => e.Cancel = !double.TryParse(e.Text, out var value);
    }
    
    public class SingleTextBox : ValidatingTextBox
    {
        protected override void OnValidateText(object sender, ValidateTextEventArgs e) => e.Cancel = !float.TryParse(e.Text, out var value);
    }
    
    public class DecimalTextBox : ValidatingTextBox
    {
        protected override void OnValidateText(object sender, ValidateTextEventArgs e) => e.Cancel = !decimal.TryParse(e.Text, out var value);
    }
    

    Note 1: When using WPF binding, you must make sure you use the class that fits the bound property type otherwise, it may lead to strange results.

    Note 2: When using floating point classes with WPF binding, make sure the binding uses the current culture to match the TryParse method I've used.

    0 讨论(0)
  • 2020-11-22 04:20

    The event handler is previewing text input. Here a regular expression matches the text input only if it is not a number, and then it is not made to entry textbox.

    If you want only letters then replace the regular expression as [^a-zA-Z].

    XAML

    <TextBox Name="NumberTextBox" PreviewTextInput="NumberValidationTextBox"/>
    

    XAML.CS FILE

    using System.Text.RegularExpressions;
    private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
    {
        Regex regex = new Regex("[^0-9]+");
        e.Handled = regex.IsMatch(e.Text);
    }
    
    0 讨论(0)
  • 2020-11-22 04:20

    How about this? Works well for me. Hope I didn't miss any edge cases...

    MyTextBox.PreviewTextInput += (sender, args) =>
    {
        if (!int.TryParse(args.Text, out _))
        {
            args.Handled = true;
        }
    };
    
    DataObject.AddPastingHandler(MyTextBox, (sender, args) =>
    {
        var isUnicodeText = args.SourceDataObject.GetDataPresent(DataFormats.UnicodeText, true);
        if (!isUnicodeText)
        {
            args.CancelCommand();
        }
    
        var data = args.SourceDataObject.GetData(DataFormats.UnicodeText) as string;
        if (!int.TryParse(data, out _))
        {
            args.CancelCommand();
        }
    });
    
    0 讨论(0)
  • 2020-11-22 04:21

    In the WPF application, you can handle this by handling TextChanged event:

    void arsDigitTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
    {
        Regex regex = new Regex("[^0-9]+");
        bool handle = regex.IsMatch(this.Text);
        if (handle)
        {
            StringBuilder dd = new StringBuilder();
            int i = -1;
            int cursor = -1;
            foreach (char item in this.Text)
            {
                i++;
                if (char.IsDigit(item))
                    dd.Append(item);
                else if(cursor == -1)
                    cursor = i;
            }
            this.Text = dd.ToString();
    
            if (i == -1)
                this.SelectionStart = this.Text.Length;
            else
                this.SelectionStart = cursor;
        }
    }
    
    0 讨论(0)
  • 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:

    <TextBox Text="{Binding NumberPagesToPrint, UpdateSourceTrigger=PropertyChanged}"/>
    

    ...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:

    <Button Template="{DynamicResource CustomButton_Flat}" Content="Set"
            Command="{Binding SetNumberPagesCommand}"/>
    

    ...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.

    0 讨论(0)
提交回复
热议问题