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

后端 未结 30 2345
悲哀的现实
悲哀的现实 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:09

    I was working with an unbound box for a simple project I was working on, so I couldn't use the standard binding approach. Consequently I created a simple hack that others might find quite handy by simply extending the existing TextBox control:

    namespace MyApplication.InterfaceSupport
    {
        public class NumericTextBox : TextBox
        {
    
    
            public NumericTextBox() : base()
            {
                TextChanged += OnTextChanged;
            }
    
    
            public void OnTextChanged(object sender, TextChangedEventArgs changed)
            {
                if (!String.IsNullOrWhiteSpace(Text))
                {
                    try
                    {
                        int value = Convert.ToInt32(Text);
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(String.Format("{0} only accepts numeric input.", Name));
                        Text = "";
                    }
                }
            }
    
    
            public int? Value
            {
                set
                {
                    if (value != null)
                    {
                        this.Text = value.ToString();
                    }
                    else 
                        Text = "";
                }
                get
                {
                    try
                    {
                        return Convert.ToInt32(this.Text);
                    }
                    catch (Exception ef)
                    {
                        // Not numeric.
                    }
                    return null;
                }
            }
        }
    }
    

    Obviously, for a floating type, you would want to parse it as a float and so on. The same principles apply.

    Then in the XAML file you need to include the relevant namespace:

    
    

    After that you can use it as a regular control:

    
    

提交回复
热议问题