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

后端 未结 30 2289
悲哀的现实
悲哀的现实 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 03:57

    I will assume that:

    1. Your TextBox for which you want to allow numeric input only has its Text property initially set to some valid number value (for example, 2.7172).

    2. Your Textbox is a child of your main window

    3. Your main window is of class Window1

    4. Your TextBox name is numericTB

    Basic idea:

    1. Add: private string previousText; to your main window class (Window1)

    2. Add: previousText = numericTB.Text; to your main window constructor

    3. Create a handler for the numericTB.TextChanged event to be something like this:

      private void numericTB_TextChanged(object sender, TextChangedEventArgs e)
      {
          double num = 0;
          bool success = double.TryParse(((TextBox)sender).Text, out num);
          if (success & num >= 0)
              previousText = ((TextBox)sender).Text;
          else
              ((TextBox)sender).Text = previousText;
      }
      

    This will keep setting previousText to numericTB.Text as long as it is valid, and set numericTB.Text to its last valid value if the user writes something that you don't like. Of course, this is just basic idea, and it is just "idiot resistant", not "idiot proof". It doesn't handle the case in which the user messes with spaces, for example. So here is a complete solution which I think is "idiot proof", and if I'm wrong please tell me:

    1. Content of your Window1.xaml file:

      <Window x:Class="IdiotProofNumericTextBox.Window1"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          Title="Window1" Height="300" Width="300">
          <Grid>
              <TextBox Height="30" Width="100" Name="numericTB" TextChanged="numericTB_TextChanged"/>
          </Grid>
      </Window>
      
    2. Content of your Window.xaml.cs file:

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Windows;
      using System.Windows.Controls;
      using System.Windows.Data;
      using System.Windows.Documents;
      using System.Windows.Input;
      using System.Windows.Media;
      using System.Windows.Media.Imaging;
      using System.Windows.Navigation;
      using System.Windows.Shapes;
      
      namespace IdiotProofNumericTextBox
      {
          public partial class Window1 : Window
          {
              private string previousText;
      
              public Window1()
              {
                  InitializeComponent();
                  previousText = numericTB.Text;
              }
      
              private void numericTB_TextChanged(object sender, TextChangedEventArgs e)
              {
                  if (string.IsNullOrEmpty(((TextBox)sender).Text))
                      previousText = "";
                  else
                  {
                      double num = 0;
                      bool success = double.TryParse(((TextBox)sender).Text, out num);
                      if (success & num >= 0)
                      {
                          ((TextBox)sender).Text.Trim();
                          previousText = ((TextBox)sender).Text;
                      }
                      else
                      {
                          ((TextBox)sender).Text = previousText;
                          ((TextBox)sender).SelectionStart = ((TextBox)sender).Text.Length;
                      }
                  }
              }
          }
      }
      

    And that's it. If you have many TextBoxes then I recommend creating a CustomControl that inherits from TextBox, so you can wrap previousText and numericTB_TextChanged up in a separate file.

    0 讨论(0)
  • 2020-11-22 03:58

    This is an improved solution of WilPs answer. My improvements are:

    • Improved behaviour on Del and Backspace buttons
    • Added EmptyValue property, if empty string is inappropriate
    • Fixed some minor typos
    /// <summary>
    ///     Regular expression for Textbox with properties: 
    ///         <see cref="RegularExpression"/>, 
    ///         <see cref="MaxLength"/>,
    ///         <see cref="EmptyValue"/>.
    /// </summary>
    public class TextBoxInputRegExBehaviour : Behavior<TextBox>
    {
        #region DependencyProperties
        public static readonly DependencyProperty RegularExpressionProperty =
            DependencyProperty.Register("RegularExpression", typeof(string), typeof(TextBoxInputRegExBehaviour), new FrameworkPropertyMetadata(".*"));
    
        public string RegularExpression
        {
            get { return (string)GetValue(RegularExpressionProperty); }
            set { SetValue(RegularExpressionProperty, value); }
        }
    
        public static readonly DependencyProperty MaxLengthProperty =
            DependencyProperty.Register("MaxLength", typeof(int), typeof(TextBoxInputRegExBehaviour),
                                            new FrameworkPropertyMetadata(int.MinValue));
    
        public int MaxLength
        {
            get { return (int)GetValue(MaxLengthProperty); }
            set { SetValue(MaxLengthProperty, value); }
        }
    
        public static readonly DependencyProperty EmptyValueProperty =
            DependencyProperty.Register("EmptyValue", typeof(string), typeof(TextBoxInputRegExBehaviour), null);
    
        public string EmptyValue
        {
            get { return (string)GetValue(EmptyValueProperty); }
            set { SetValue(EmptyValueProperty, value); }
        }
        #endregion
    
        /// <summary>
        ///     Attach our behaviour. Add event handlers
        /// </summary>
        protected override void OnAttached()
        {
            base.OnAttached();
    
            AssociatedObject.PreviewTextInput += PreviewTextInputHandler;
            AssociatedObject.PreviewKeyDown += PreviewKeyDownHandler;
            DataObject.AddPastingHandler(AssociatedObject, PastingHandler);
        }
    
        /// <summary>
        ///     Deattach our behaviour. remove event handlers
        /// </summary>
        protected override void OnDetaching()
        {
            base.OnDetaching();
    
            AssociatedObject.PreviewTextInput -= PreviewTextInputHandler;
            AssociatedObject.PreviewKeyDown -= PreviewKeyDownHandler;
            DataObject.RemovePastingHandler(AssociatedObject, PastingHandler);
        }
    
        #region Event handlers [PRIVATE] --------------------------------------
    
        void PreviewTextInputHandler(object sender, TextCompositionEventArgs e)
        {
            string text;
            if (this.AssociatedObject.Text.Length < this.AssociatedObject.CaretIndex)
                text = this.AssociatedObject.Text;
            else
            {
                //  Remaining text after removing selected text.
                string remainingTextAfterRemoveSelection;
    
                text = TreatSelectedText(out remainingTextAfterRemoveSelection)
                    ? remainingTextAfterRemoveSelection.Insert(AssociatedObject.SelectionStart, e.Text)
                    : AssociatedObject.Text.Insert(this.AssociatedObject.CaretIndex, e.Text);
            }
    
            e.Handled = !ValidateText(text);
        }
    
        /// <summary>
        ///     PreviewKeyDown event handler
        /// </summary>
        void PreviewKeyDownHandler(object sender, KeyEventArgs e)
        {
            if (string.IsNullOrEmpty(this.EmptyValue))
                return;
    
            string text = null;
    
            // Handle the Backspace key
            if (e.Key == Key.Back)
            {
                if (!this.TreatSelectedText(out text))
                {
                    if (AssociatedObject.SelectionStart > 0)
                        text = this.AssociatedObject.Text.Remove(AssociatedObject.SelectionStart - 1, 1);
                }
            }
            // Handle the Delete key
            else if (e.Key == Key.Delete)
            {
                // If text was selected, delete it
                if (!this.TreatSelectedText(out text) && this.AssociatedObject.Text.Length > AssociatedObject.SelectionStart)
                {
                    // Otherwise delete next symbol
                    text = this.AssociatedObject.Text.Remove(AssociatedObject.SelectionStart, 1);
                }
            }
    
            if (text == string.Empty)
            {
                this.AssociatedObject.Text = this.EmptyValue;
                if (e.Key == Key.Back)
                    AssociatedObject.SelectionStart++;
                e.Handled = true;
            }
        }
    
        private void PastingHandler(object sender, DataObjectPastingEventArgs e)
        {
            if (e.DataObject.GetDataPresent(DataFormats.Text))
            {
                string text = Convert.ToString(e.DataObject.GetData(DataFormats.Text));
    
                if (!ValidateText(text))
                    e.CancelCommand();
            }
            else
                e.CancelCommand();
        }
        #endregion Event handlers [PRIVATE] -----------------------------------
    
        #region Auxiliary methods [PRIVATE] -----------------------------------
    
        /// <summary>
        ///     Validate certain text by our regular expression and text length conditions
        /// </summary>
        /// <param name="text"> Text for validation </param>
        /// <returns> True - valid, False - invalid </returns>
        private bool ValidateText(string text)
        {
            return (new Regex(this.RegularExpression, RegexOptions.IgnoreCase)).IsMatch(text) && (MaxLength == int.MinValue || text.Length <= MaxLength);
        }
    
        /// <summary>
        ///     Handle text selection
        /// </summary>
        /// <returns>true if the character was successfully removed; otherwise, false. </returns>
        private bool TreatSelectedText(out string text)
        {
            text = null;
            if (AssociatedObject.SelectionLength <= 0) 
                return false;
    
            var length = this.AssociatedObject.Text.Length;
            if (AssociatedObject.SelectionStart >= length)
                return true;
    
            if (AssociatedObject.SelectionStart + AssociatedObject.SelectionLength >= length)
                AssociatedObject.SelectionLength = length - AssociatedObject.SelectionStart;
    
            text = this.AssociatedObject.Text.Remove(AssociatedObject.SelectionStart, AssociatedObject.SelectionLength);
            return true;
        }
        #endregion Auxiliary methods [PRIVATE] --------------------------------
    }
    

    Usage is pretty straightforward:

    <i:Interaction.Behaviors>
        <behaviours:TextBoxInputRegExBehaviour RegularExpression="^\d+$" MaxLength="9" EmptyValue="0" />
    </i:Interaction.Behaviors>
    
    0 讨论(0)
  • 2020-11-22 04:00

    If you do not want to write a lot of code to do a basic function (I don't know why people make long methods) you can just do this:

    1. Add namespace:

      using System.Text.RegularExpressions;
      
    2. In XAML, set a TextChanged property:

      <TextBox x:Name="txt1" TextChanged="txt1_TextChanged"/>
      
    3. In WPF under txt1_TextChanged method, add Regex.Replace:

      private void txt1_TextChanged(object sender, TextChangedEventArgs e)
      {
          txt1.Text = Regex.Replace(txt1.Text, "[^0-9]+", "");
      }
      
    0 讨论(0)
  • 2020-11-22 04:01

    The Extented WPF Toolkit has one: NumericUpDown enter image description here

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

    Another approach will be using an attached behavior, I implemented my custom TextBoxHelper class, which can be used on textboxes all over my project. Because I figured that subscribing to the events for every textboxes and in every individual XAML file for this purpose can be time consuming.

    The TextBoxHelper class I implemented has these features:

    • Filtering and accepting only numbers in Double, Int, Uint and Natural format
    • Filtering and accepting only Even or Odd numbers
    • Handling paste event handler to prevent pasting invalid text into our numeric textboxes
    • Can set a Default Value which will be used to prevent invalid data as the last shot by subscribing to the textboxes TextChanged event

    Here is the implementation of TextBoxHelper class:

    public static class TextBoxHelper
    {
        #region Enum Declarations
    
        public enum NumericFormat
        {
            Double,
            Int,
            Uint,
            Natural
        }
    
        public enum EvenOddConstraint
        {
            All,
            OnlyEven,
            OnlyOdd
        }
    
        #endregion
    
        #region Dependency Properties & CLR Wrappers
    
        public static readonly DependencyProperty OnlyNumericProperty =
            DependencyProperty.RegisterAttached("OnlyNumeric", typeof(NumericFormat?), typeof(TextBoxHelper),
                new PropertyMetadata(null, DependencyPropertiesChanged));
        public static void SetOnlyNumeric(TextBox element, NumericFormat value) =>
            element.SetValue(OnlyNumericProperty, value);
        public static NumericFormat GetOnlyNumeric(TextBox element) =>
            (NumericFormat) element.GetValue(OnlyNumericProperty);
    
    
        public static readonly DependencyProperty DefaultValueProperty =
            DependencyProperty.RegisterAttached("DefaultValue", typeof(string), typeof(TextBoxHelper),
                new PropertyMetadata(null, DependencyPropertiesChanged));
        public static void SetDefaultValue(TextBox element, string value) =>
            element.SetValue(DefaultValueProperty, value);
        public static string GetDefaultValue(TextBox element) => (string) element.GetValue(DefaultValueProperty);
    
    
        public static readonly DependencyProperty EvenOddConstraintProperty =
            DependencyProperty.RegisterAttached("EvenOddConstraint", typeof(EvenOddConstraint), typeof(TextBoxHelper),
                new PropertyMetadata(EvenOddConstraint.All, DependencyPropertiesChanged));
        public static void SetEvenOddConstraint(TextBox element, EvenOddConstraint value) =>
            element.SetValue(EvenOddConstraintProperty, value);
        public static EvenOddConstraint GetEvenOddConstraint(TextBox element) =>
            (EvenOddConstraint)element.GetValue(EvenOddConstraintProperty);
    
        #endregion
    
        #region Dependency Properties Methods
    
        private static void DependencyPropertiesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (!(d is TextBox textBox))
                throw new Exception("Attached property must be used with TextBox.");
    
            switch (e.Property.Name)
            {
                case "OnlyNumeric":
                {
                    var castedValue = (NumericFormat?) e.NewValue;
    
                    if (castedValue.HasValue)
                    {
                        textBox.PreviewTextInput += TextBox_PreviewTextInput;
                        DataObject.AddPastingHandler(textBox, TextBox_PasteEventHandler);
                    }
                    else
                    {
                        textBox.PreviewTextInput -= TextBox_PreviewTextInput;
                        DataObject.RemovePastingHandler(textBox, TextBox_PasteEventHandler);
                    }
    
                    break;
                }
    
                case "DefaultValue":
                {
                    var castedValue = (string) e.NewValue;
    
                    if (castedValue != null)
                    {
                        textBox.TextChanged += TextBox_TextChanged;
                    }
                    else
                    {
                        textBox.TextChanged -= TextBox_TextChanged;
                    }
    
                    break;
                }
            }
        }
    
        #endregion
    
        private static void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            var textBox = (TextBox)sender;
    
            string newText;
    
            if (textBox.SelectionLength == 0)
            {
                newText = textBox.Text.Insert(textBox.SelectionStart, e.Text);
            }
            else
            {
                var textAfterDelete = textBox.Text.Remove(textBox.SelectionStart, textBox.SelectionLength);
    
                newText = textAfterDelete.Insert(textBox.SelectionStart, e.Text);
            }
    
            var evenOddConstraint = GetEvenOddConstraint(textBox);
    
            switch (GetOnlyNumeric(textBox))
            {
                case NumericFormat.Double:
                {
                    if (double.TryParse(newText, out double number))
                    {
                        switch (evenOddConstraint)
                        {
                            case EvenOddConstraint.OnlyEven:
    
                                if (number % 2 != 0)
                                    e.Handled = true;
                                else
                                    e.Handled = false;
    
                                break;
    
                            case EvenOddConstraint.OnlyOdd:
    
                                if (number % 2 == 0)
                                    e.Handled = true;
                                else
                                    e.Handled = false;
    
                                break;
                        }
                    }
                    else
                        e.Handled = true;
    
                    break;
                }
    
                case NumericFormat.Int:
                {
                    if (int.TryParse(newText, out int number))
                    {
                        switch (evenOddConstraint)
                        {
                            case EvenOddConstraint.OnlyEven:
    
                                if (number % 2 != 0)
                                    e.Handled = true;
                                else
                                    e.Handled = false;
    
                                break;
    
                            case EvenOddConstraint.OnlyOdd:
    
                                if (number % 2 == 0)
                                    e.Handled = true;
                                else
                                    e.Handled = false;
    
                                break;
                        }
                    }
                    else
                        e.Handled = true;
    
                    break;
                }
    
                case NumericFormat.Uint:
                {
                    if (uint.TryParse(newText, out uint number))
                    {
                        switch (evenOddConstraint)
                        {
                            case EvenOddConstraint.OnlyEven:
    
                                if (number % 2 != 0)
                                    e.Handled = true;
                                else
                                    e.Handled = false;
    
                                break;
    
                            case EvenOddConstraint.OnlyOdd:
    
                                if (number % 2 == 0)
                                    e.Handled = true;
                                else
                                    e.Handled = false;
    
                                break;
                        }
                    }
                    else
                        e.Handled = true;
    
                    break;
                }
    
                case NumericFormat.Natural:
                {
                    if (uint.TryParse(newText, out uint number))
                    {
                        if (number == 0)
                            e.Handled = true;
                        else
                        {
                            switch (evenOddConstraint)
                            {
                                case EvenOddConstraint.OnlyEven:
    
                                    if (number % 2 != 0)
                                        e.Handled = true;
                                    else
                                        e.Handled = false;
    
                                    break;
    
                                case EvenOddConstraint.OnlyOdd:
    
                                    if (number % 2 == 0)
                                        e.Handled = true;
                                    else
                                        e.Handled = false;
    
                                    break;
                            }
                        }
                    }
                    else
                        e.Handled = true;
    
                    break;
                }
            }
        }
    
        private static void TextBox_PasteEventHandler(object sender, DataObjectPastingEventArgs e)
        {
            var textBox = (TextBox)sender;
    
            if (e.DataObject.GetDataPresent(typeof(string)))
            {
                var clipboardText = (string) e.DataObject.GetData(typeof(string));
    
                var newText = textBox.Text.Insert(textBox.SelectionStart, clipboardText);
    
                var evenOddConstraint = GetEvenOddConstraint(textBox);
    
                switch (GetOnlyNumeric(textBox))
                {
                    case NumericFormat.Double:
                    {
                        if (double.TryParse(newText, out double number))
                        {
                            switch (evenOddConstraint)
                            {
                                case EvenOddConstraint.OnlyEven:
    
                                    if (number % 2 != 0)
                                        e.CancelCommand();
    
                                    break;
    
                                case EvenOddConstraint.OnlyOdd:
    
                                    if (number % 2 == 0)
                                        e.CancelCommand();
    
                                    break;
                            }
                        }
                        else
                            e.CancelCommand();
    
                        break;
                    }
    
                    case NumericFormat.Int:
                    {
                        if (int.TryParse(newText, out int number))
                        {
                            switch (evenOddConstraint)
                            {
                                case EvenOddConstraint.OnlyEven:
    
                                    if (number % 2 != 0)
                                        e.CancelCommand();
    
                                    break;
    
                                case EvenOddConstraint.OnlyOdd:
    
                                    if (number % 2 == 0)
                                        e.CancelCommand();
    
    
                                    break;
                            }
                        }
                        else
                            e.CancelCommand();
    
                        break;
                    }
    
                    case NumericFormat.Uint:
                    {
                        if (uint.TryParse(newText, out uint number))
                        {
                            switch (evenOddConstraint)
                            {
                                case EvenOddConstraint.OnlyEven:
    
                                    if (number % 2 != 0)
                                        e.CancelCommand();
    
                                    break;
    
                                case EvenOddConstraint.OnlyOdd:
    
                                    if (number % 2 == 0)
                                        e.CancelCommand();
    
    
                                    break;
                            }
                        }
                        else
                            e.CancelCommand();
    
                        break;
                    }
    
                    case NumericFormat.Natural:
                    {
                        if (uint.TryParse(newText, out uint number))
                        {
                            if (number == 0)
                                e.CancelCommand();
                            else
                            {
                                switch (evenOddConstraint)
                                {
                                    case EvenOddConstraint.OnlyEven:
    
                                        if (number % 2 != 0)
                                            e.CancelCommand();
    
                                        break;
    
                                    case EvenOddConstraint.OnlyOdd:
    
                                        if (number % 2 == 0)
                                            e.CancelCommand();
    
                                        break;
                                }
                            }
                        }
                        else
                        {
                            e.CancelCommand();
                        }
    
                        break;
                    }
                }
            }
            else
            {
                e.CancelCommand();
            }
        }
    
        private static void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            var textBox = (TextBox)sender;
    
            var defaultValue = GetDefaultValue(textBox);
    
            var evenOddConstraint = GetEvenOddConstraint(textBox);
    
            switch (GetOnlyNumeric(textBox))
            {
                case NumericFormat.Double:
                {
                    if (double.TryParse(textBox.Text, out double number))
                    {
                        switch (evenOddConstraint)
                        {
                            case EvenOddConstraint.OnlyEven:
    
                                if (number % 2 != 0)
                                    textBox.Text = defaultValue;
    
                                break;
    
                            case EvenOddConstraint.OnlyOdd:
    
                                if (number % 2 == 0)
                                    textBox.Text = defaultValue;
    
                                break;
                        }
                    }
                    else
                        textBox.Text = defaultValue;
    
                    break;
                }
    
                case NumericFormat.Int:
                {
                    if (int.TryParse(textBox.Text, out int number))
                    {
                        switch (evenOddConstraint)
                        {
                            case EvenOddConstraint.OnlyEven:
    
                                if (number % 2 != 0)
                                    textBox.Text = defaultValue;
    
                                break;
    
                            case EvenOddConstraint.OnlyOdd:
    
                                if (number % 2 == 0)
                                    textBox.Text = defaultValue;
    
                                break;
                        }
                    }
                    else
                        textBox.Text = defaultValue;
    
                    break;
                }
    
                case NumericFormat.Uint:
                {
                    if (uint.TryParse(textBox.Text, out uint number))
                    {
                        switch (evenOddConstraint)
                        {
                            case EvenOddConstraint.OnlyEven:
    
                                if (number % 2 != 0)
                                    textBox.Text = defaultValue;
    
                                break;
    
                            case EvenOddConstraint.OnlyOdd:
    
                                if (number % 2 == 0)
                                    textBox.Text = defaultValue;
    
                                break;
                        }
                    }
                    else
                        textBox.Text = defaultValue;
    
                    break;
                }
    
                case NumericFormat.Natural:
                {
                    if (uint.TryParse(textBox.Text, out uint number))
                    {
                        if(number == 0)
                            textBox.Text = defaultValue;
                        else
                        {
                            switch (evenOddConstraint)
                            {
                                case EvenOddConstraint.OnlyEven:
    
                                    if (number % 2 != 0)
                                        textBox.Text = defaultValue;
    
                                    break;
    
                                case EvenOddConstraint.OnlyOdd:
    
                                    if (number % 2 == 0)
                                        textBox.Text = defaultValue;
    
                                    break;
                            }
                        }
                    }
                    else
                    {
                        textBox.Text = defaultValue;
                    }
    
                    break;
                }
            }
        }
    }
    

    And here is some example of its easy usage:

    <TextBox viewHelpers:TextBoxHelper.OnlyNumeric="Double"
             viewHelpers:TextBoxHelper.DefaultValue="1"/>
    

    Or

    <TextBox viewHelpers:TextBoxHelper.OnlyNumeric="Natural"
             viewHelpers:TextBoxHelper.DefaultValue="3"
             viewHelpers:TextBoxHelper.EvenOddConstraint="OnlyOdd"/>
    

    Note that my TextBoxHelper resides in the viewHelpers xmlns alias.

    I hope that this implementation eases some other one's work :)

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

    In Windows Forms it was easy; you can add an event for KeyPress and everything works easily. However, in WPF that event isn't there. But there is a much easier way for it.

    The WPF TextBox has the TextChanged event which is general for everything. It includes pasting, typing and whatever that can come up to your mind.

    So you can do something like this:

    XAML:

    <TextBox name="txtBox1" ... TextChanged="TextBox_TextChanged"/>
    

    CODE BEHIND:

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e) {
        string s = Regex.Replace(((TextBox)sender).Text, @"[^\d.]", "");
        ((TextBox)sender).Text = s;
    }
    

    This also accepts . , if you don't want it, just remove it from the regex statement to be @[^\d].

    Note: This event can be used on many TextBox'es as it uses the sender object's Text. You only write the event once and can use it for multiple TextBox'es.

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