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

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

    Now I know this question has an accepted answer, but personally, I find it a bit confusing and I believe it should be easier than that. So I'll try to demonstrate how I got it to work as best as I can:

    In Windows Forms, there's an event called KeyPress which is perfectly good for this kind of task. But that doesn't exist in WPF, so instead, we'll be using the PreviewTextInput event. Also, for the validation, I believe one can use a foreach to loop through the textbox.Text and check if it matches ;) the condition, but honestly, this is what regular expressions are for.

    One more thing before we dive into the holy code. For the event to be fired, one can do two things:

    1. Use XAML to tell the program which function to call:
    2. Do it in the Loaded event of the form (which the textBox is in): textBox.PreviewTextInput += onlyNumeric;

    I think the second method is better because in situations like this, you'll mostly be required to apply the same condition (regex) to more than one TextBox and you don't want to repeat yourself!.

    Finally, here's how you'd do it:

    private void onlyNumeric(object sender, TextCompositionEventArgs e)
    {
        string onlyNumeric = @"^([0-9]+(.[0-9]+)?)$";
        Regex regex = new Regex(onlyNumeric);
        e.Handled = !regex.IsMatch(e.Text);
    }
    

提交回复
热议问题