The objective is to implement the reversed version of StringToDoubleConverter
but without writing too many redundancies. I love DRY (Don't Repeat Yourself) design principle.
public class StringToDoubleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return double.TryParse(value as string, out var x) ? x : double.NaN;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value is double x ? x.ToString("f3") : string.Empty;
}
}
Here are my approaches. Any suggestions or comments are welcome.
Version A: Inheritance
public class DoubleToStringConverter : StringToDoubleConverter, IValueConverter
{
public new object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return base.ConvertBack(value, targetType, parameter, culture);
}
public new object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return base.Convert(value, targetType, parameter, culture);
}
}
Version B: Composition
public class DoubleToStringConverter : IValueConverter
{
private static readonly StringToDoubleConverter std = new();
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return std.ConvertBack(value, targetType, parameter, culture);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return std.Convert(value, targetType, parameter, culture);
}
}
sealed
. \$\endgroup\$IValueConverter
definition? \$\endgroup\$IValueConverter
is in your link. Two classes are needed for two different usages. \$\endgroup\$