DFLayoutTimeFieldProperties.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Globalization;
  3. namespace InABox.Core
  4. {
  5. public class DFLayoutTimeFieldProperties : DFLayoutFieldProperties<TimeSpan, TimeSpan?>
  6. {
  7. [EditorSequence(-995)]
  8. [TimeOfDayEditor]
  9. public override TimeSpan Default { get; set; }
  10. public DFLayoutTimeFieldProperties()
  11. {
  12. Format = "hh:mm";
  13. }
  14. public string Format { get; set; }
  15. public override string FormatValue(TimeSpan? value)
  16. {
  17. var time = value ?? default;
  18. return string.IsNullOrWhiteSpace(Format) || string.Equals(Format, "hh:mm")
  19. ? Math.Truncate(time.TotalHours).ToString("#00") + ":" + time.Minutes.ToString("D2")
  20. : string.Format("{0:" + Format.Replace(":", "\\:") + "}", time);
  21. }
  22. public override void SerializeValue(DFSaveStorageEntry entry, TimeSpan? value)
  23. {
  24. if (value.HasValue)
  25. {
  26. entry.SetValue(value.Value.ToString("c"));
  27. }
  28. }
  29. public override TimeSpan? DeserializeValue(DFLoadStorageEntry entry)
  30. {
  31. var value = entry.GetValue();
  32. if (value is TimeSpan time)
  33. return time;
  34. if (TimeSpan.TryParseExact(value as string, "c", CultureInfo.InvariantCulture, TimeSpanStyles.None, out var result))
  35. return result;
  36. return null;
  37. }
  38. public override TimeSpan GetValue(TimeSpan? value)
  39. {
  40. return value ?? Default;
  41. }
  42. protected override void LoadProperties()
  43. {
  44. base.LoadProperties();
  45. Format = GetProperty("Format", "hh:mm");
  46. }
  47. protected override void SaveProperties()
  48. {
  49. base.SaveProperties();
  50. SetProperty("Format", Format);
  51. }
  52. }
  53. }