Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 NumericUpDown custom control from Microsoft. But so far it seems like NumericUpDown (supported by WPF or not) is not going to provide the functionality that I want. The way my application is designed, nobody in their right mind is going to want to mess with the arrows. They don't make any practical sense, in the context of my application.

So I'm looking for a simple way to make a standard WPF TextBox accept only the characters that I want. Is this possible? Is it practical?

like image 345
Giffyguy Avatar asked Aug 12 '09 20:08

Giffyguy


People also ask

How do I make a TextBox only accept a number?

In our webpage with the definition of textbox we can add an onkeypress event for accepting only numbers. It will not show any message but it will prevent you from wrong input. It worked for me, user could not enter anything except number.

How do you make a text box non editable in WPF?

Solution 1Add IsReadOnly = "True" in xaml of textbox.


1 Answers

Add a preview text input event. Like so: <TextBox PreviewTextInput="PreviewTextInput" />.

Then inside that set the e.Handled if the text isn't allowed. e.Handled = !IsTextAllowed(e.Text);

I use a simple regex in IsTextAllowed method to see if I should allow what they've typed. In my case I only want to allow numbers, dots and dashes.

private static readonly Regex _regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text private static bool IsTextAllowed(string text) {     return !_regex.IsMatch(text); } 

If you want to prevent pasting of incorrect data hook up the DataObject.Pasting event DataObject.Pasting="TextBoxPasting" as shown here (code excerpted):

// Use the DataObject.Pasting Handler  private void TextBoxPasting(object sender, DataObjectPastingEventArgs e) {     if (e.DataObject.GetDataPresent(typeof(String)))     {         String text = (String)e.DataObject.GetData(typeof(String));         if (!IsTextAllowed(text))         {             e.CancelCommand();         }     }     else     {         e.CancelCommand();     } } 
like image 115
Ray Avatar answered Sep 28 '22 03:09

Ray