WPF中的双向百分比格式化绑定

Ale*_*x J 8 .net data-binding wpf

我有这个文本框:

<TextBox Text="{Binding Path=TaxFactor, StringFormat=P}" />
Run Code Online (Sandbox Code Playgroud)

它正确显示0.055%,但它无法返回.当我输入百分比时,由于符号百分比而失败.如果我尝试只编写一个数字5,我会500%改为.我必须写0.05它才能工作.

我是否必须编写自定义转换器以获得我的百分比?如果是这样,我如何绕过特定于语言环境的百分比格式?

Chr*_*isF 10

您需要编写自定义转换器.注意:此值假定值存储在0到100的范围内,而不是0到1.

public object Convert(object value, Type targetType, object parameter,
                      System.Globalization.CultureInfo culture)
{
    if (string.IsNullOrEmpty(value.ToString())) return 0;

    if (value.GetType() == typeof(double)) return (double)value / 100;

    if (value.GetType() == typeof(decimal)) return (decimal)value / 100;    

    return value;
}

public object ConvertBack(object value, Type targetType, object parameter,
                          System.Globalization.CultureInfo culture)
{
    if (string.IsNullOrEmpty(value.ToString())) return 0;

    var trimmedValue = value.ToString().TrimEnd(new char[] { '%' });

    if (targetType == typeof(double))
    {
        double result;
        if (double.TryParse(trimmedValue, out result))
            return result;
        else
            return value;
    }

    if (targetType == typeof(decimal))
    {
        decimal result;
        if (decimal.TryParse(trimmedValue, out result))
            return result;
        else
            return value;
    }
    return value;
}
Run Code Online (Sandbox Code Playgroud)

这样称呼:

<TextBox Text="{Binding Path=TaxFactor, Mode=TwoWay, StringFormat=P, 
         Converter={StaticResource percentStringFormatConverter} />
Run Code Online (Sandbox Code Playgroud)

这是来自某些Silverlight代码,但应该与WPF一起使用


Ale*_*x J 6

添加到ChrisF的答案,我最终使用的转换器(仅用于小数):

class DecimalPercentageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,
                  System.Globalization.CultureInfo culture)
    {
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter,
                              System.Globalization.CultureInfo culture)
    {
        if (targetType != typeof(decimal) || value == null)
            return value;

        string str = value.ToString();

        if (String.IsNullOrWhiteSpace(str))
            return 0M;

        str = str.TrimEnd(culture.NumberFormat.PercentSymbol.ToCharArray());

        decimal result = 0M;
        if (decimal.TryParse(str, out result)) {
            result /= 100;
        }

        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)