C#C
C#13mo ago
Samuel

Decimal in clamped TextBox

I'm implementing a numerical TextBox that may clamp entered values between a min and max value. I achieved this by overriding the MetaData for the Text property with a TwoWay binding by default and an OnTextChanged handler.

One of the hurdles along the way was partially entered values such as -, 0., 1.3, etc. I overcame this with a regex.

The issue I have is that I'm unable to enter a decimal into the TextBox despite being allowed by the regex ^(-?\d+\.|-0?)$.

Here is my on changed handler.
private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var s = (string)e.NewValue;
    var regex = new Regex(@"^(-?\d+\.|-0?)$");
    if (string.IsNullOrEmpty(s) || regex.Match(s).Success)
        return;

    if (double.TryParse((string)e.NewValue, out var oldValue))
    {
        if (!(bool)d.GetValue(EnforceRangeProperty))
            return;

        var min = (double)d.GetValue(MinProperty);
        var max = (double)d.GetValue(MaxProperty);

        var newValue = Math.Max(min, oldValue);
        newValue = Math.Min(max, newValue);

        // ReSharper disable once CompareOfFloatsByEqualityOperator
        if (newValue == oldValue)
            return;

        d.SetValue(TextProperty, newValue.ToString(CultureInfo.InvariantCulture));
        return;
    }

    // If we can't parse the text, revert to the old value.
    d.SetValue(TextProperty, (string)e.OldValue);
}


What changes can I make to allow for the entry of a decimal point?

Edit: I've also realised that I cannot enter -0, subsequently -0.
Was this page helpful?