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

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

    
    

    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.

提交回复
热议问题