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

后端 未结 30 2292
悲哀的现实
悲哀的现实 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条回答
  • 2020-11-22 04:10

    Here is a very simple and easy way to do this using MVVM.

    Bind your textBox with an integer property in the view model, and this will work like a gem ... it will even show validation when a non-integer is entered in the textbox.

    XAML code:

    <TextBox x:Name="contactNoTxtBox"  Text="{Binding contactNo}" />
    

    View model code:

    private long _contactNo;
    public long contactNo
    {
        get { return _contactNo; }
        set
        {
            if (value == _contactNo)
                return;
            _contactNo = value;
            OnPropertyChanged();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 04:13

    Here I have a simple solution inspired by Ray's answer. This should be sufficient to identify any form of number.

    This solution can also be easily modified if you want only positive numbers, integer values or values accurate to a maximum number of decimal places, etc.


    As suggested in Ray's answer, you need to first add a PreviewTextInput event:

    <TextBox PreviewTextInput="TextBox_OnPreviewTextInput"/>
    

    Then put the following in the code behind:

    private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        var textBox = sender as TextBox;
        // Use SelectionStart property to find the caret position.
        // Insert the previewed text into the existing text in the textbox.
        var fullText = textBox.Text.Insert(textBox.SelectionStart, e.Text);
    
        double val;
        // If parsing is successful, set Handled to false
        e.Handled = !double.TryParse(fullText, out val);
    }
    

    To invalid whitespace, we can add NumberStyles:

    using System.Globalization;
    
    private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        var textBox = sender as TextBox;
        // Use SelectionStart property to find the caret position.
        // Insert the previewed text into the existing text in the textbox.
        var fullText = textBox.Text.Insert(textBox.SelectionStart, e.Text);
    
        double val;
        // If parsing is successful, set Handled to false
        e.Handled = !double.TryParse(fullText, 
                                     NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, 
                                     CultureInfo.InvariantCulture,
                                     out val);
    }
    
    0 讨论(0)
  • 2020-11-22 04:13

    For those looking for a quick and very simple implementation for this type of problem using only integers and decimal, in your XAML file, add a PreviewTextInput property to your TextBoxand then in your xaml.cs file use:

    private void Text_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        e.Handled = !char.IsDigit(e.Text.Last()) && !e.Text.Last() == '.';
    }
    

    It's kind of redundant to keep checking the entire string every time unless, as others have mentioned, you're doing something with scientific notation (albeit, if you're adding certain characters like 'e', a simple regex adding symbols/characters is really simple and illustrated in other answers). But for simple floating point values, this solution will suffice.

    Written as a one-liner with a lambda expression:

    private void Text_PreviewTextInput(object sender, TextCompositionEventArgs e) => e.Handled = !char.IsDigit(e.Text.Last() && !e.Text.Last() == '.');
    
    0 讨论(0)
  • 2020-11-22 04:17

    I used some of what was already here and put my own twist on it using a behavior so I don't have to propagate this code throughout a ton of Views...

    public class AllowableCharactersTextBoxBehavior : Behavior<TextBox>
    {
        public static readonly DependencyProperty RegularExpressionProperty =
             DependencyProperty.Register("RegularExpression", typeof(string), typeof(AllowableCharactersTextBoxBehavior),
             new FrameworkPropertyMetadata(".*"));
        public string RegularExpression
        {
            get
            {
                return (string)base.GetValue(RegularExpressionProperty);
            }
            set
            {
                base.SetValue(RegularExpressionProperty, value);
            }
        }
    
        public static readonly DependencyProperty MaxLengthProperty =
            DependencyProperty.Register("MaxLength", typeof(int), typeof(AllowableCharactersTextBoxBehavior),
            new FrameworkPropertyMetadata(int.MinValue));
        public int MaxLength
        {
            get
            {
                return (int)base.GetValue(MaxLengthProperty);
            }
            set
            {
                base.SetValue(MaxLengthProperty, value);
            }
        }
    
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.PreviewTextInput += OnPreviewTextInput;
            DataObject.AddPastingHandler(AssociatedObject, OnPaste);
        }
    
        private void OnPaste(object sender, DataObjectPastingEventArgs e)
        {
            if (e.DataObject.GetDataPresent(DataFormats.Text))
            {
                string text = Convert.ToString(e.DataObject.GetData(DataFormats.Text));
    
                if (!IsValid(text, true))
                {
                    e.CancelCommand();
                }
            }
            else
            {
                e.CancelCommand();
            }
        }
    
        void OnPreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            e.Handled = !IsValid(e.Text, false);
        }
    
        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.PreviewTextInput -= OnPreviewTextInput;
            DataObject.RemovePastingHandler(AssociatedObject, OnPaste);
        }
    
        private bool IsValid(string newText, bool paste)
        {
            return !ExceedsMaxLength(newText, paste) && Regex.IsMatch(newText, RegularExpression);
        }
    
        private bool ExceedsMaxLength(string newText, bool paste)
        {
            if (MaxLength == 0) return false;
    
            return LengthOfModifiedText(newText, paste) > MaxLength;
        }
    
        private int LengthOfModifiedText(string newText, bool paste)
        {
            var countOfSelectedChars = this.AssociatedObject.SelectedText.Length;
            var caretIndex = this.AssociatedObject.CaretIndex;
            string text = this.AssociatedObject.Text;
    
            if (countOfSelectedChars > 0 || paste)
            {
                text = text.Remove(caretIndex, countOfSelectedChars);
                return text.Length + newText.Length;
            }
            else
            {
                var insert = Keyboard.IsKeyToggled(Key.Insert);
    
                return insert && caretIndex < text.Length ? text.Length : text.Length + newText.Length;
            }
        }
    }
    

    Here is the relevant view code:

    <TextBox MaxLength="50" TextWrapping="Wrap" MaxWidth="150" Margin="4"
     Text="{Binding Path=FileNameToPublish}" >
         <interactivity:Interaction.Behaviors>
             <v:AllowableCharactersTextBoxBehavior RegularExpression="^[0-9.\-]+$" MaxLength="50" />
         </interactivity:Interaction.Behaviors>
    </TextBox>
    
    0 讨论(0)
  • 2020-11-22 04:17
    e.Handled = (int)e.Key >= 43 || (int)e.Key <= 34;
    

    in preview keydown event of textbox.

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

    For developers who want their text fields to accept unsigned numbers only such as socket ports and so on:

    WPF

    <TextBox PreviewTextInput="Port_PreviewTextInput" MaxLines="1"/>
    

    C#

    private void Port_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        e.Handled = !int.TryParse(e.Text, out int x);
    }
    
    0 讨论(0)
提交回复
热议问题