How do I get a TextBox to only accept numeric input in WPF?

How to Make a TextBox Only Accept Numeric Input in WPF 😎💻
Are you tired of users freely entering non-numeric characters in your WPF TextBox? Do you want to restrict input to only numbers without having to deal with cumbersome arrow controls? Look no further! In this guide, we'll walk you through the easy and practical steps to achieve this.
Understanding the Problem
The challenge at hand is to allow users to input digits and decimal points while disallowing any other characters or signs.
Exploring the Options
You might have come across the NumericUpDown control for Windows Forms or the custom NumericUpDown control provided by Microsoft for WPF. But if you don't want to deal with the arrow controls, those options might not be the best fit for your needs.
The Simple Solution
Luckily, we have a simpler and more practical solution for you! By leveraging the power of regular expressions in WPF, you can easily validate and control the input of your TextBox. Here's how you can do it:
Start by adding an event handler to the
PreviewTextInputevent of your TextBox. This event fires before the actual text is updated, giving us the chance to validate and filter the input.
<TextBox PreviewTextInput="TextBox_PreviewTextInput" />In the code-behind of your XAML file, implement the
TextBox_PreviewTextInputevent handler method.
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
var textBox = (TextBox)sender;
var proposedText = textBox.Text + e.Text;
// Use a regular expression to validate the proposed text
if (!Regex.IsMatch(proposedText, "^[0-9]*\\.?[0-9]*$"))
{
e.Handled = true; // Prevent the input from being applied
}
}In the regular expression
^[0-9]*\\.?[0-9]*$, we specify the pattern for valid input. The expression allows for zero or more digits ([0-9]*), an optional decimal point (\\.?), and zero or more digits after the decimal point ([0-9]*).
That's it! You're Done! 🥳
By implementing this simple solution, you can now restrict your TextBox to accept only numeric input, including decimals. Users won't be able to enter any other characters or signs.
Engage with the Community
We hope this guide has helped you solve your problem efficiently. If you have any questions or need further assistance, don't hesitate to reach out to the vibrant WPF community. Share your thoughts and experiences in the comments section below, and let's learn from each other!
And remember, sharing is caring! If you found this guide useful, spread the word by sharing it with your fellow developers who might benefit from it. Happy coding! 👩💻👨💻
Thank you for reading!
Take Your Tech Career to the Next Level
Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.



