DFLayoutTimeFieldProperties.cs 1.9 KB

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