Two way percentage formatted binding in WPF

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

I have this textbox:


It correctly displays 0.05 as 5

2条回答
  •  醉酒成梦
    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:

    
                                                            
提交回复
热议问题