App

[wpf]only numeric input allow at textbox

마피아9 2010. 2. 24. 01:54

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 to see if I should allow what they've typed. In my case I only want to allow numbers, dots and dashes.

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

If you want to prevent pasting of incorrect data hook up the DataObject.Pasting eventDataObject.Pasting="TextBoxPasting" as shown here(Masking input to a WPF TextBox  참조)