Home >Backend Development >C++ >How Can I Restrict Input in a WPF TextBox to Only Numeric Values and a Decimal Point?
Restricting WPF TextBox Input to Numeric Values and a Decimal Point
Need a WPF TextBox that accepts only numbers and a decimal point, without allowing any signs? While a NumericUpDown
control might seem like a solution, it may not fit your application's design. A more flexible approach uses the PreviewTextInput
and DataObject.Pasting
events.
Add the PreviewTextInput
event to your TextBox definition like this: <TextBox PreviewTextInput="PreviewTextInput"></TextBox>
.
The PreviewTextInput
event handler checks if the input is valid using a regular expression. This example allows only digits, periods (.), and hyphens (-):
<code class="language-csharp">private static readonly Regex _regex = new Regex("[^0-9.-]+"); // Regex for disallowed characters private static bool IsTextAllowed(string text) { return !_regex.IsMatch(text); } private void PreviewTextInput(object sender, TextCompositionEventArgs e) { e.Handled = !IsTextAllowed(e.Text); }</code>
To prevent pasting invalid data, handle the DataObject.Pasting
event:
<code class="language-csharp">private void TextBoxPasting(object sender, DataObjectPastingEventArgs e) { if (e.DataObject.GetDataPresent(typeof(String))) { string text = (string)e.DataObject.GetData(typeof(String)); if (!IsTextAllowed(text)) { e.CancelCommand(); } } else { e.CancelCommand(); } }</code>
These methods ensure your TextBox accepts only numeric input, providing a clean and efficient solution tailored to your application's design.
The above is the detailed content of How Can I Restrict Input in a WPF TextBox to Only Numeric Values and a Decimal Point?. For more information, please follow other related articles on the PHP Chinese website!