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

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

    
    

    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);
    }
    

提交回复
热议问题