I'm implementing a validation rule for a property of type double bound to a TextBox. The problem is that when I enter a 0 in the decimal digits, if the resulting number is accepted by the rule, WPF erases that last 0 as it understands it to be dummy mathematically. This prevents me from entering a non-0 digit after it.
For example I cannot input 5.101 because when I reach 5.10, WPF erases the 0 and I get back to 5.1.
I can workaround this by returning a failed ValidationResult when I catch 5.10, as in that case WPF does not remove the 0. But this is handled as a failure by the style (red border) and is confusing to the user.
Any idea on a better workaround?
The validation is handled in a class inheriting from ValidationRule, and the Validate method is this.
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
double dValue = 0.0;
string sValue;
string definition = "Enter number in [ " + Min + "; " + Max + "]";
// Catch non-double, empty, minus sign
try
{
sValue = (string)value;
if (sValue == "-")
return new ValidationResult(false, definition);
else if (sValue.Length > 0)
dValue = double.Parse(sValue);
else // Empty entry
return new ValidationResult(false, definition);
}
catch (Exception ex)
{
return new ValidationResult(false, "Invalid entry: " + ex.Message);
}
// Forbid finishing with dot but return false to allow keyboard input
if (sValue.EndsWith("."))
return new ValidationResult(false, "Cannot end with '.'");
// Check range
if (dValue < Min || dValue > Max)
return new ValidationResult(false, definition);
else
{
// Workaround to allow input of 0
if (sValue.Contains(".") && sValue.EndsWith("0"))
return new ValidationResult(false, "Accepted");
else
return new ValidationResult(true, null);
}
}
The problem seems to be connected to feedback from the object. When I change from TwoWay to something else, the validation no longer prevents the input of 0s. Unfortunately I do need the TextBox to display the content of my object the first time I bind it. But after that I would be ok with just OneWayToSource as I can just reset the DataContext to update. Is there a way for the TextBox to be filled with the property value when I attach the object to the DataContext, while in OneWayToSource (not by explicity setting its Text I mean)?