PercentageConverter.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Globalization;
  3. using System.Windows.Data;
  4. namespace SWRIS.Converters
  5. {
  6. public class PercentageConverter : IValueConverter
  7. {
  8. /// <summary>
  9. /// 将值转换为百分比显示(例如:0.85 -> "85%")
  10. /// </summary>
  11. public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  12. {
  13. if (value == null) return "0";
  14. try
  15. {
  16. // 支持多种数值类型
  17. double numericValue = System.Convert.ToDouble(value);
  18. // 检查是否有参数指定小数位数
  19. int decimalPlaces = 0;
  20. if (parameter != null && int.TryParse(parameter.ToString(), out int places))
  21. {
  22. decimalPlaces = places;
  23. }
  24. // 转换为百分比(乘以100)
  25. double percentage = numericValue * 100;
  26. // 格式化输出
  27. string format = $"F{decimalPlaces}";
  28. return percentage.ToString(format);
  29. }
  30. catch
  31. {
  32. return "0";
  33. }
  34. }
  35. /// <summary>
  36. /// 将百分比字符串转换回数值(例如:"85%" -> 0.85)
  37. /// </summary>
  38. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  39. {
  40. if (value == null) return 0.0;
  41. string stringValue = value.ToString();
  42. try
  43. {
  44. // 移除百分比符号和空格
  45. stringValue = stringValue.Replace("%", "").Trim();
  46. if (double.TryParse(stringValue, NumberStyles.Any, culture, out double result))
  47. {
  48. // 转换回小数(除以100)
  49. return result / 100.0;
  50. }
  51. return 0.0;
  52. }
  53. catch
  54. {
  55. return 0.0;
  56. }
  57. }
  58. }
  59. }