Managing the input in your project is very important. In this post, you can see how create a numeric field in WPF, using the regular expressions.

XAML:

<TextBox PreviewTextInput="NumberValidationTextBox"></TextBox>

Code behind:

private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
    Regex regex = new Regex("[^0-9]+");
    e.Handled = regex.IsMatch(e.Text);
}

If you also want to set the max length of this field, you can simply use the attribute maxLenght:

<TextBox MaxLength="5" PreviewTextInput="NumberValidationTextBox"></TextBox>
Advertisements