| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- using System;
- using System.Globalization;
- using System.Windows.Data;
- namespace SWRIS.Converters
- {
- public class PercentageConverter : IValueConverter
- {
- /// <summary>
- /// 将值转换为百分比显示(例如:0.85 -> "85%")
- /// </summary>
- public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
- {
- if (value == null) return "0";
- try
- {
- // 支持多种数值类型
- double numericValue = System.Convert.ToDouble(value);
- // 检查是否有参数指定小数位数
- int decimalPlaces = 0;
- if (parameter != null && int.TryParse(parameter.ToString(), out int places))
- {
- decimalPlaces = places;
- }
- // 转换为百分比(乘以100)
- double percentage = numericValue * 100;
- // 格式化输出
- string format = $"F{decimalPlaces}";
- return percentage.ToString(format);
- }
- catch
- {
- return "0";
- }
- }
- /// <summary>
- /// 将百分比字符串转换回数值(例如:"85%" -> 0.85)
- /// </summary>
- public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
- {
- if (value == null) return 0.0;
- string stringValue = value.ToString();
- try
- {
- // 移除百分比符号和空格
- stringValue = stringValue.Replace("%", "").Trim();
- if (double.TryParse(stringValue, NumberStyles.Any, culture, out double result))
- {
- // 转换回小数(除以100)
- return result / 100.0;
- }
- return 0.0;
- }
- catch
- {
- return 0.0;
- }
- }
- }
- }
|