Search code examples
c#wpftextbox

C# - Restrict value entered to between 0.0 to 1.0 in a textbox


I am new to C# and WPF. I have a textbox in my WPF application and I want to limit the value entered by user in the textbox between 0.0 and 1.0. How do I do that?

Any help would be really helpful.


Solution

  • Something like this might work for you, as you will also get the value:

    double valueEntered;
    if (!double.TryParse(textBoxName.Text, out valueEntered)
        // value is not a valid double
        return;
    else
        if (valueEntered < 0 || valueEntered > 1)
            // value is valid
            return;
        else
            // value is not valid
            return;
    

    For a better implementation you should show us the XAML and the code-behind of your Window.