Home > Backend Development > C++ > How to Restrict a WPF TextBox to Accept Only Numeric Input?

How to Restrict a WPF TextBox to Accept Only Numeric Input?

Susan Sarandon
Release: 2025-01-29 14:16:10
Original
759 people have browsed it

How to Restrict a WPF TextBox to Accept Only Numeric Input?

Only the digital input

in WPF Textbox WPF applications often need to limit the TextBox to only receive digital input. Whether it is an integer or a decimal, this is necessary for various applications.

Use PreviewTextInput and ISTEXTALLOWED

In order to achieve this function, you can use Incident:

PreviewTextInput In the event processing program, you can use the

method to control whether the user is allowed to input:
<code class="language-xml"><TextBox PreviewTextInput="PreviewTextInput"></TextBox></code>
Copy after login

PreviewTextInput This method uses regular expressions to verify the input to meet the needs of the application. IsTextAllowed

Prevent data objects from pasteting
<code class="language-csharp">private static readonly Regex _regex = new Regex("[^0-9.-]+"); //匹配不允许的文本的正则表达式
private static bool IsTextAllowed(string text)
{
    return !_regex.IsMatch(text);
}

private void PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    if (!IsTextAllowed(e.Text))
    {
        e.Handled = true;
    }
}</code>
Copy after login

In order to further limit the input, you can use the

event:

This ensures that the data that pasted to the TextBox also meet the required input conditions. Note that is corrected here DataObject.Pasting, which is more in line with the parameter type of the

event. For the incident, the code remains unchanged.
<code class="language-xml"><TextBox DataObject.Pasting="TextBoxPasting"></TextBox></code>
Copy after login

The above is the detailed content of How to Restrict a WPF TextBox to Accept Only Numeric Input?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template