I want to make a text box in my wpf application that will only accept integer values. if someone types between [az], the text box will reject it. Thus, it will not appear in the text box
You can handle the PreviewTextInput event:
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) { // Filter out non-digit text input foreach (char c in e.Text) if (!Char.IsDigit(c)) { e.Handled = true; break; } }
You can add an event descriptor TextChangedand see what was entered (it is necessary to check all the text each time to prevent pasting letters from the clipboard).
TextChanged
Also see a very good example of creating a maskable editbox on CodeProject .
WPF KeyDown :
KeyDown
private void MyTextBox_KeyDown(object sender, KeyDownEventArgs e) { e.Handled = true; }
this simple piece of code should do the trick. You might also want to check for overflow (numbers too large)
private void IntegerTextBox_TextChanged(object sender, EventArgs e) { for (int i = 0; i < Text.Length; i++) { int c = Text[i]; if (c < '0' || c > '9') { Text = Text.Remove(i, 1); } } }
Bind it to the Integer property. WPF will independently validate without any additional problems.