This question already has an answer here:
I would like to create a TextBox that only accepts numeric values, in a specific range. What is the best way to implement such TextBox?
I thought about deriving TextBox and to override the validation and coercion of the TextProperty. However, I am not sure how to do this, and I understand that deriving WPF control is generally not recommended.
Edit:
What I needed was a very basic textbox that filters out all key presses which are not digits. The easiest way to achieve it is to handle the TextBox.PreviewTextInput event:
private void textBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
int result;
if (!validateStringAsNumber(e.Text,out result,false))
{
e.Handled = true;
}
}
(validateStringAsNumber is my function that primarily use Int.TryParse)
Some of the suggested solutions are probably better, but for the simple functionality I needed this solution is the easiest and quickest to implement while sufficient for my needs.
The overall best why is to use the override method
OnKeyPressed
for the textbox like. Here is the code for the override using the static Char MethodIsDigit
.That is all you really need to do.
This would be my preferred approach:
Most implementations I have seen so far are using the PreviewTextInput event to implement the correct mask behavior. This one inherits from TextBox and this one uses attached properties. Both use .Net's MaskedTextProvider to provide the correct mask behaviour, but if you just want a simple 'numbers only' textbox you don't need this class.
In my humble opinion, the best way to fulfill this requirement is using only
OnTextChanged
event because it can handle the digit from keystroke and also be able to handle Copy+Paste from clipboard too. I hope that my VB code shown below can throw some light on this.