Add a preview text input event. For example: <TextBox PreviewTextInput="PreviewTextInput" /> .
Then inside this set is e.Handled if the text is not allowed.
e.Handled = !IsTextAllowed(e.Text);
I use a simple regular expression in IsTextAllowed to see if they allow me what they typed. In my case, I just want to allow numbers, periods, and dashes.
private static bool IsTextAllowed(string text) { Regex regex = new Regex("[^0-9.-]+");
If you want to prevent the insertion of incorrect data, turn DataObject.Pasting="TextBoxPasting" DataObject.Pasting DataObject.Pasting="TextBoxPasting" , as shown here (the code is written out):
// 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(); } }
source share