How do I get a TextBox to only accept numeric input in WPF?
The event handler is previewing text input. Here a regular expression matches the text input only if it is not a number, and then it is not made to entry textbox.
If you want only letters then replace the regular expression as [^a-zA-Z]
.
XAML
<TextBox Name="NumberTextBox" PreviewTextInput="NumberValidationTextBox"/>
XAML.CS FILE
using System.Text.RegularExpressions;
private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex("[^0-9]+");
e.Handled = regex.IsMatch(e.Text);
}
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();
}
}