The code below does not allow the entry in which it is binded to allow the field to begin with a decimal point. The Entry has a placeholder of 0.
Please help. Thanks
public class DecimalCommaDisplayConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null || !(value is decimal)) throw new ArgumentException("This converter may only be used on values of type decimal.");
var decimalValue = (decimal)value;
//In the UI represent 0 as empty string.
if (decimalValue == default)
{
return string.Empty;
}
//Format the string with maximum of 4 decimal places and commas as appropriate.
// Examples: 0.23, 1.2, 1,234.5678
return decimalValue.ToString("#,0.####");
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null && !(value is string)) throw new ArgumentException("This converter may only be used on values of type string.");
string stringValue = (string)value;
//In the UI, 0 is represented as an empty string.
if (string.IsNullOrEmpty(stringValue))
{
return 0.0m;
}
if(decimal.TryParse((stringValue).Replace(",", ""), out decimal result))
{
return result;
}
//If the value isn't convertable, then just return it and let the TextChanged handler convert it back.
return stringValue;
}