How to Allow only numeric input in a Textbox in WPF ?


This content was proof-read by Grammarly. You can Try Grammary for FREE

If you are looking at ways to accept only digits and decimal points (numeric input) for a textbox in WPF , you could do it by following the below steps.

How to Allow only numeric input in a Textbox in WPF ?

  1. Add the Event PreviewTextInput for the Textbox in the XAML.
<TextBox PreviewTextInput="PreviewTextInput" />
  1. In the Xaml.cs , add the following. The regular expression is used so that it can identify if the input contains ano other characters apart from numeric input. If invalid entry , return e.handled = false.
using System.Text.RegularExpressions;
private void PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    Regex regex = new Regex("[^0-9]+");
    e.Handled = regex.IsMatch(e.Text);
}
%d bloggers like this: