I am working in WPF and C#, and have run into an issue which I think stems from my converter. I have a textbox where upon page load, an INT is converted to a DOUBLE and is displayed. Example:
- Initial Value: 32.99
- Can change to:
- 24
- 24.99
- 24.9
- Unable to change to:
- 24.09
What happens is after I type 24.0, it instantly reverts to 24. I can achieve 24.09 by typing in 24.9 and then typing a 0 into the spot where I need it. I have tried to mess with my converter thinking that it was an issue with when/how I was converting it to a double but it is still producing the same results.
Here is the code for the converter:
//This takes in an int and converts it to a double with two decimal places
[ValueConversion(typeof(object), typeof(double))]
public class conDouble : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double db = System.Convert.ToDouble(value);
return (db / 100.00).ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return System.Convert.ToInt32((System.Convert.ToDouble(value) * 100));
}
}
The textbox in question with the regex:
<Page.Resources>
<system:String x:Key="regexDouble">^\d+(\.\d{1,2})?$</system:String>
</Page.Resources>
<TextBox Name="txtItemPrice" Grid.Column="12" Grid.ColumnSpan="2" Grid.Row="4" HorizontalAlignment="Stretch" VerticalAlignment="Center" IsEnabled="False"
Validation.ErrorTemplate="{StaticResource validationTemplate}"
Style="{StaticResource textStyleTextBox}">
<TextBox.Text>
<Binding Path="intPrice" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay" Converter="{StaticResource Double}">
<Binding.ValidationRules>
<classobjects:RegexValidation Expression="{StaticResource regexDouble}"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
And at last my validator:
public class RegexValidation : ValidationRule
{
private string pattern;
private Regex regex;
public string Expression
{
get { return pattern; }
set
{
pattern = value;
regex = new Regex(pattern, RegexOptions.IgnoreCase);
}
}
public RegexValidation() { }
public override ValidationResult Validate(object value, CultureInfo ultureInfo)
{
if (value == null || !regex.IsMatch(value.ToString()))
{
return new ValidationResult(false, "Illegal Characters");
}
else
{
return new ValidationResult(true, null);
}
}
}