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

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

    The following code creates a control which you will be able to use like a normal TextBox however it will only take a positive double as an input:

    In the XAML you'll be able to use this control like so:

    
    

    In the C# code add the following inside the current namespace:

    public class UnsignedDoubleBox : TextBox
        {
            public UnsignedDoubleBox()
            {
                this.PreviewTextInput += defaultPreviewTextInput;
                DataObject.AddPastingHandler(this, defaultTextBoxPasting);
            }
    
            private bool IsTextAllowed(TextBox textBox, String text)
            {
                //source: https://stackoverflow.com/questions/23397195/in-wpf-does-previewtextinput-always-give-a-single-character-only#comment89374810_23406386
                String newText = textBox.Text.Insert(textBox.CaretIndex, text);
                double res;
                return double.TryParse(newText, out res) && res >= 0;
            }
            //source: https://stackoverflow.com/a/1268648/13093413
            private void defaultTextBoxPasting(object sender, DataObjectPastingEventArgs e)
            {
                if (e.DataObject.GetDataPresent(typeof(String)))
                {
                    String text = (String)e.DataObject.GetData(typeof(String));
    
                    if (!IsTextAllowed((TextBox)sender, text))
                    {
                        e.CancelCommand();
                    }
                }
                else
                {
                    e.CancelCommand();
                }
            }
    
            private void defaultPreviewTextInput(object sender, TextCompositionEventArgs e)
            {
    
                if (IsTextAllowed((TextBox)sender, e.Text))
                {
                    e.Handled = false;
                }
                else
                {
                    e.Handled = true;
                }
            }
    
        }
    

提交回复
热议问题