You can build a format string with the desired number of zeroes:
string.Format(culture, "{0:0." + new string('0', Convert.ToInt32(parameter)) + "}"
Frage
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?"
Lösung
You can build a format string with the desired number of zeroes:
string.Format(culture, "{0:0." + new string('0', Convert.ToInt32(parameter)) + "}"