TextBoxTimeSpanMaskBehavior.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Windows.Controls;
  4. using System.Windows.Input;
  5. using Microsoft.Xaml.Behaviors;
  6. namespace InABox.WPF;
  7. public class TextBoxTimeSpanMaskBehavior : Behavior<TextBox>
  8. {
  9. private bool bFirst = true;
  10. private List<Tuple<int, char>> _separators = new List<Tuple<int, char>>();
  11. private string _format = "HH:mm";
  12. public string Format
  13. {
  14. get => _format;
  15. set
  16. {
  17. _format = value;
  18. ReloadSeparators();
  19. }
  20. }
  21. private void ReloadSeparators()
  22. {
  23. _separators.Clear();
  24. var formatted = new TimeSpanToStringConverter(_format).Convert(DateTime.Now.TimeOfDay);
  25. int iOffset = 0;
  26. for (int i=0; i<formatted.Length; i++)
  27. {
  28. var ch = formatted[i];
  29. if (!Char.IsNumber(ch))
  30. {
  31. _separators.Add(new Tuple<int, char>(i - iOffset, ch));
  32. iOffset++;
  33. }
  34. }
  35. }
  36. public TextBoxTimeSpanMaskBehavior(string? format)
  37. {
  38. Format = String.IsNullOrWhiteSpace(format)
  39. ? "HH:mm"
  40. : format;
  41. }
  42. protected override void OnAttached()
  43. {
  44. AssociatedObject.PreviewTextInput += PreviewTextInput;
  45. AssociatedObject.TextChanged += TextChanged;
  46. AssociatedObject.MouseDoubleClick += MouseDoubleClick;
  47. base.OnAttached();
  48. }
  49. protected override void OnDetaching()
  50. {
  51. AssociatedObject.MouseDoubleClick -= MouseDoubleClick;
  52. AssociatedObject.TextChanged -= TextChanged;
  53. AssociatedObject.PreviewTextInput -= PreviewTextInput;
  54. base.OnDetaching();
  55. }
  56. private void MouseDoubleClick(object sender, MouseButtonEventArgs e)
  57. {
  58. AssociatedObject.Text = String.Format("{0:" + Format + "}", DateTime.Now.TimeOfDay);
  59. }
  60. private void PreviewTextInput(object sender, TextCompositionEventArgs e)
  61. {
  62. bFirst = false;
  63. if (!int.TryParse(e.Text, out int _))
  64. e.Handled = true;
  65. }
  66. private void TextChanged(object sender, TextChangedEventArgs e)
  67. {
  68. var plaintext = AssociatedObject.Text?.Trim() ?? "";
  69. foreach (var separator in _separators)
  70. plaintext = plaintext.Replace(separator.Item2.ToString(), "");
  71. var decorated = plaintext;
  72. for (int i = _separators.Count - 1; i >= 0; i--)
  73. {
  74. if (plaintext.Length >= _separators[i].Item1)
  75. decorated = decorated.Insert(_separators[i].Item1, _separators[i].Item2.ToString());
  76. }
  77. AssociatedObject.Text = decorated;
  78. if (bFirst)
  79. AssociatedObject.SelectAll();
  80. else
  81. AssociatedObject.Select(AssociatedObject.Text.Length, 0);
  82. e.Handled = true;
  83. }
  84. }