Check answer to this question.
According to that you need to handle PreviewTextInput event of TextBox like so: <TextBox PreviewTextInput="PreviewTextInput" />.
Then inside of it you should set if the text isn't allowed: e.Handled = !IsTextAllowed(e.Text);
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 check user's paste input as well, then you should hook up DataObject.Pasting event as well. So your xaml would look like:
<TextBox PreviewTextInput="PreviewTextInput"
DataObject.Pasting="PastingHandler" />
And PastingHandler:
private void PastingHandler(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();
}
}
Hope this helps.