0

I created a ValueConverter between Double and String so that my textboxes have a given number of decimal places.

I need, though, to be able to pass an integer as a parameter to the ValueConverter methods, so that I can have a different number of decimal places on any given textbox, and yet use the same converter.

My converter code is here:

[ValueConversion(typeof(Double), typeof(String))]
public class DoubleToStringPontoVirgula : IValueConverter {

    // Converte um double em uma string separada por vírgula com tantas casas depois da vírgula
    public object Convert(object value,
                          Type targetType,
                          object parameter, // I would like to use this!!
                          System.Globalization.CultureInfo culture) {

        string resultado = string.Format("{0:0.0}", // Shouldn't be a hardcoded format!
                                           value);
        return resultado;

    }

    // Converte uma string separada por ponto OU vírgula em um double
    public object ConvertBack(object value,
                              Type targetType,
                              object parameter,
                              System.Globalization.CultureInfo culture) {

        string entrada = value as string;

        double resultado = System.Convert.ToDouble(entrada.Replace('.', ','));

        return resultado;

    }

}

In the XAML, I would like to pass the parameter like this (using "2" places as example):

<TextBox Text="{Binding Peso, Converter={StaticResource DoubleToStringPontoVirgula}, ConverterParameter=2}"/>

The question is: "How can I take the integer passed as parametar argument and use it as the number of decimal places in the string-formatting expression?"

heltonbiker
  • 26,657
  • 28
  • 137
  • 252
  • And your problem is.......? – Nikhil Agrawal Oct 21 '13 at 13:42
  • 1
    Why have a converter at all? You could use the [StringFormat](http://msdn.microsoft.com/en-us/library/system.windows.data.bindingbase.stringformat.aspx) property instead. – Clemens Oct 21 '13 at 13:46
  • why do you need converter... why dont directly specify StringFormat on binding? – Nitin Oct 21 '13 at 13:46
  • The converter is most necessary because I want the user to input decimal places either using "." or ",". The `ConvertBack` ended up being necessary, so I am using both `Convert` and `ConvertBack` for the tweaking. – heltonbiker Oct 21 '13 at 13:48

1 Answers1

1

You can build a format string with the desired number of zeroes:

string.Format(culture, "{0:0." + new string('0', Convert.ToInt32(parameter)) + "}"
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964