#948 – Complete Example of Limiting TextBox Input
November 12, 2013 1 Comment
If you want to limit text allowed as input to a TextBox, a full strategy for checking text being input should include handling the PreviewKeyDown and PreviewTextInput events, as well as implementing a pasting handler. Below is a full example that limits text input to alphabetic characters only.
<TextBox Name="txtMyText" Margin="5" Height="100" TextWrapping="Wrap" AcceptsReturn="True" VerticalScrollBarVisibility="Auto" PreviewTextInput="TextBox_PreviewTextInput" PreviewKeyDown="TextBox_PreviewKeyDown"/>
public MainWindow() { this.InitializeComponent(); DataObject.AddPastingHandler(txtMyText, PasteHandler); } private bool IsAlphabetic(string s) { Regex r = new Regex(@"^[a-zA-Z]+$"); return r.IsMatch(s); } private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) { // Prohibit non-alphabetic if (!IsAlphabetic(e.Text)) e.Handled = true; } private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e) { // Prohibit space if (e.Key == Key.Space) e.Handled = true; } private void PasteHandler(object sender, DataObjectPastingEventArgs e) { TextBox tb = sender as TextBox; bool textOK = false; if (e.DataObject.GetDataPresent(typeof(string))) { // Allow pasting only alphabetic string pasteText = e.DataObject.GetData(typeof(string)) as string; if (IsAlphabetic(pasteText)) textOK = true; } if (!textOK) e.CancelCommand(); }