I have a textbox bound to a decimal value (property) and when I type the "3." it does not allow me to enter as it parses it back to 3 and hence I lose the ".". I tried the solutions like Delay/LostFocus etc but that did not work for me, from WPF validation rule preventing decimal entry in textbox?.
I have now written a IValueConverter class and I am obviously not doing it correctly. Here is the code:
[ValueConversion(typeof(decimal), typeof(string))]
public class DecimalToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//return Decimal.Parse(value.ToString());
if (value == null) return Decimal.Zero;
if (!(value is string)) return value;
string s = (string)value;
int dotCount = s.Count(f => f == '.');
Decimal d;
bool parseValid = Decimal.TryParse(s, out d);
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("^[-+]?([0-9]*?[.])?[0-9]*$");
bool b = regex.IsMatch(s);
if (dotCount == 1 && b)
{
return s;
}
return d;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value != null ? value.ToString() : "";
}
}
XAML
<TextBox x:Name="ValueTextBox" Grid.Column="0" Grid.RowSpan="2" VerticalContentAlignment="Center" Text ="{Binding Value, Converter={StaticResource DecimalToStringConverter}}" PreviewTextInput="ValueTextBox_OnPreviewTextInput" TextWrapping="Wrap" MouseWheel="ValueTextBox_MouseWheel" PreviewKeyDown="ValueTextBox_PreviewKeyDown" PreviewKeyUp="ValueTextBox_PreviewKeyUp" TextChanged="ValueTextBox_TextChanged" BorderThickness="1,1,0,1"/>
Please advise how I can correct this... Thanks