I am using a ValueConverter to display double types as currency. I want to make sure the entry is valid, so I tried using this validation method I made up. My only problem seems to be that I can’t select the whole value (ie $500.00) and type anything. If the ‘$’ is not selected, everything seems fine. How can I fix this?
XAML:
<TextBox Text="{Binding Converter={StaticResource MoneyConverter}, Path=fr}"
PreviewTextInput="ValidateMoney" DataObject.Pasting="TextBox_Pasting"/>
Code behind:
private void ValidateMoney(object sender, TextCompositionEventArgs e) {
Regex rgx = new Regex(@"^(\$)[0-9]*[.]{0,1}[0-9]*$|^[.][0-9]+$|^[0-9]*[.]{0,1}[0-9]*$");
e.Handled = !rgx.IsMatch((sender as TextBox).Text.Insert((sender as TextBox).SelectionStart, e.Text));
}
public class MoneyConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
if (value != null) {
double d;
string temp = value.ToString();
if (double.TryParse(temp, out d)) {
return String.Format("{0:C}", d);
} else {
return value;
}
} else {
return value;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
if (value != null) {
double d;
string temp = value.ToString();
if (double.TryParse(temp, out d)) {
return String.Format("{0:C}", d);
} else {
return value;
}
} else {
return value;
}
}
}
Your approach to including the dollar sign is correct, though the parentheses are unnecessary. It is sufficient to write this:
^\$.You can simplify your regular expression a lot:
{0,1}can be replaced with?.Try this:
Or using capturing groups to reduce clutter:
Some other points:
TryParseis affected by the current culture.1.990means different things depending on your culture.ToStringalso depends on culture. The"{0:C}"format doesn’t guarantee a dollar sign.$.990. That might be what you want, but it looks a little odd to me.decimalrather thandoubleto store monetary amounts. Thedoubletype can’t store1.99exactly, butdecimalcan.[.]with the equivalent\.but that is just a matter of taste. Both do the same thing.