如何将绑定格式化为双倍######。##使用文化?

时间:2013-09-24 12:38:45

标签: c# wpf string-formatting

我的ViewModel上有一个double值,想要绑定TextBlock的Text,这样:

128228.094545格式化为128228 [x] 09,其中[x]是根据计算机文化设置的小数分隔符。

我试过了:

Text="{Binding Value, StringFormat='{}{0:F2}'}"

不起作用:无论正确的小数点分隔符号如何,该值都会显示128228.09。

Text="{Binding Value, StringFormat='{}{0:N2}'}"

呈现我不想要的数字分组符号([d],y在en-US中):128 [d] 228 [x] 09

Text="{Binding Value, StringFormat='{}{0:0.00}'}"

显然不起作用。

什么是正确的格式化字符串?

2 个答案:

答案 0 :(得分:1)

我认为你的第一个定义是正确的。事情是格式总是根据设置的文化来完成。不知道你究竟在使用什么,但这取决于如何为你的应用程序设置文化。

这是一篇很棒的博客文章,描述了WPF,因为手动定义文化存在一些问题......

http://www.west-wind.com/weblog/posts/2009/Jun/14/WPF-Bindings-and-CurrentCulture-Formatting

答案 1 :(得分:1)

我认为问题在于,当数据绑定中使用StringFormat时,它不符合当前的文化。

过去我使用简单的IValueConverter格式化值。如果您的应用程序允许用户指定所有数字的格式选项,例如此选项非常有用,例如小数位数。或者,您可以使用ConverterParameter指定格式字符串,只需返回:

String.Format(CultureInfo.CurrentCulture, converterParameter, value)

如果您不需要使用前缀或后缀包围该值,则以下转换器应允许您转换为格式化值或从格式化值转换:

public class StringFormatConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
                          object parameter, CultureInfo culture)
    {
        var parameterString = parameter as string;
        if (value != null && parameterString != null)
        {
            return String.Format(CultureInfo.CurrentCulture, "{0:"+ parameterString + "}", value);
        }
        else
        {           
            return string.Empty;
        }
    }


    public object ConvertBack(object value, Type targetType,
                              object parameter, CultureInfo culture)
    {
        if (targetType == typeof (double))
        {
            return System.Convert.ToDouble(value, CultureInfo.CurrentCulture);
        }
        else if (targetType == typeof(int))
        {
            return System.Convert.ToInt32(value, CultureInfo.CurrentCulture);
        }
        // Any other supported types
        else
        {
            throw new NotImplementedException();
        }
    }
}