Two way percentage formatted binding in WPF

前端 未结 2 1336
盖世英雄少女心
盖世英雄少女心 2021-01-05 03:08

I have this textbox:


It correctly displays 0.05 as 5

相关标签:
2条回答
  • 2021-01-05 03:36

    Adding to ChrisF's answer, the converter I ended up using (only for decimals):

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-05 03:46

    You need to write a custom converter. NOTE: this one assumes that the values are stored in the range 0 to 100 rather than 0 to 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;
    }
    

    The call it like this:

    <TextBox Text="{Binding Path=TaxFactor, Mode=TwoWay, StringFormat=P, 
             Converter={StaticResource percentStringFormatConverter} />
    

    this is from some Silverlight code, but should work with WPF

    0 讨论(0)
提交回复
热议问题