【问题标题】:Variable number of decimal places in Double to String ValueConverterDouble to String ValueConverter 中的可变小数位数
【发布时间】:2013-10-21 13:41:02
【问题描述】:

我在 DoubleString 之间创建了一个 ValueConverter,以便我的文本框有给定的小数位数。

不过,我需要能够将整数作为参数传递给 ValueConverter 方法,这样我就可以在任何给定的文本框上使用不同的小数位数,同时使用相同的转换器。

我的转换器代码在这里:

[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;

    }

}

在 XAML 中,我想像这样传递参数(以“2”个位置为例):

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

问题是:“如何将作为parametar 参数传递的整数用作字符串格式表达式中的小数位数?”

【问题讨论】:

  • 你的问题是......?
  • 为什么要有转换器?您可以改用StringFormat 属性。
  • 为什么需要转换器...为什么不直接在绑定时指定StringFormat?
  • 转换器是最必要的,因为我希望用户使用“。”输入小数位。或者 ”,”。 ConvertBack 最终是必要的,所以我同时使用 ConvertConvertBack 进行调整。

标签: c# wpf xaml string-formatting ivalueconverter


【解决方案1】:

您可以使用所需的零数构建格式字符串:

string.Format(culture, "{0:0." + new string('0', Convert.ToInt32(parameter)) + "}"

【讨论】:

  • 这成功了!我不知道您使用的 String 构造函数。谢谢!
猜你喜欢
  • 2012-09-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-17
  • 2011-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-06
相关资源
最近更新 更多