Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wpf converters with different decimal number

I have a lot of numbers to deal with from my UI. I want some of them to be no decimal places, some to be 2 decimals, and others to be however they are entered (3 or 4 decimal places).

I have a converter named DoubleToStringConverter like this:

[ValueConversion(typeof(double), typeof(string))]
public class DoubleToStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value == null ? null : ((double)value).ToString("#,0.##########");
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        double retValue;
        if (double.TryParse(value as string, out retValue))
        {
            return retValue;
        }
        return DependencyProperty.UnsetValue;
    }
}

Is there a way to write just one converter to achieve this? It seems there is no way to have a parameterized converter. The StringFormat in xaml seems to conver string to other type of data. It does not allow to display a substring from xaml.

I can only think of making IntegerToStringConverter, Double2ToStringConverter, Double3ToStringConverter, etc. But I'd like to see whether there is a more efficient way.

like image 510
Unplug Avatar asked Feb 15 '23 04:02

Unplug


1 Answers

You can pass the number of decimal points to use as the parameter, which can then be specified in XAML via ConverterParameter within the binding.

That being said, for formatting numbers, you don't actually need a converter at all. Bindings support StringFormat directly, which can be used to do the formatting entirely in XAML:

<TextBox Text="{Binding Path=TheDoubleValue, StringFormat=0:N2} />
like image 182
Reed Copsey Avatar answered Feb 19 '23 19:02

Reed Copsey