Home > Backend Development > C++ > How Can I Restrict Input in a WPF TextBox to Only Numeric Values and a Decimal Point?

How Can I Restrict Input in a WPF TextBox to Only Numeric Values and a Decimal Point?

Patricia Arquette
Release: 2025-01-29 14:11:08
Original
261 people have browsed it

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>
Copy after login

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>
Copy after login

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!

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