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
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.