I am trying to make text box accept only specific characters.
My TextBox is bound to the following:
private string _CompanyID;
public string
You should use a custom UI element there that restricts the input on the view-side using “classic” solutions like change listeners.
For example, you can just create a simple subtype of TextBox
that overrides the OnPreviewTextInput
method. There, you can decide when some input should go through, or when you want to prevent it.
For example, this is a custom TextBox that takes only characters from the ASCII alphabet:
public class AlphabetTextBox : TextBox
{
private static readonly Regex regex = new Regex("^[a-zA-Z]+$");
protected override void OnPreviewTextInput(TextCompositionEventArgs e)
{
if (!regex.IsMatch(e.Text))
e.Handled = true;
base.OnPreviewTextInput(e);
}
}
Of course, you could also make the regular expression a property of the text box and allow people to set it from XAML. That way, you would get a very reusable component which you can use for various applications.