TimeSpanToStringMillisecondsConverter.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. namespace OINA.Extender.WPF.Testharness
  2. {
  3. using System;
  4. using System.Globalization;
  5. using System.Windows.Data;
  6. using System.Windows.Markup;
  7. /// <summary>
  8. /// Converts between <see cref="TimeSpan"/> and number of milliseconds as a <see cref="string" />.
  9. /// </summary>
  10. [ValueConversion(typeof(TimeSpan), typeof(string))]
  11. public class TimeSpanToStringMillisecondsConverter : IValueConverter
  12. {
  13. /// <summary>
  14. /// Converts a <see cref="TimeSpan"/> to number of milliseconds as a <see cref="string" />.
  15. /// </summary>
  16. /// <param name="value">The value produced by the binding source.</param>
  17. /// <param name="targetType">The type of the binding target property.</param>
  18. /// <param name="parameter">The converter parameter to use.</param>
  19. /// <param name="culture">The culture to use in the converter.</param>
  20. /// <returns>A converted value. If the method returns null, the valid null value is used.</returns>
  21. public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  22. {
  23. try
  24. {
  25. var timeSpan = (TimeSpan)value;
  26. return timeSpan.TotalMilliseconds.ToString(culture);
  27. }
  28. catch
  29. {
  30. return 0;
  31. }
  32. }
  33. /// <summary>
  34. /// Converts number of milliseconds as a <see cref="string" /> to a <see cref="TimeSpan"/>.
  35. /// </summary>
  36. /// <param name="value">The value that is produced by the binding target.</param>
  37. /// <param name="targetType">The type to convert to.</param>
  38. /// <param name="parameter">The converter parameter to use.</param>
  39. /// <param name="culture">The culture to use in the converter.</param>
  40. /// <returns>A converted value. If the method returns null, the valid null value is used.</returns>
  41. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  42. {
  43. try
  44. {
  45. var timeSpan = (string)value;
  46. return TimeSpan.FromMilliseconds(int.Parse(timeSpan, culture));
  47. }
  48. catch
  49. {
  50. return TimeSpan.Zero;
  51. }
  52. }
  53. }
  54. }