DateTimePicker.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Windows;
  5. using System.Windows.Controls;
  6. using System.Windows.Controls.Primitives;
  7. using System.Windows.Data;
  8. using System.Windows.Input;
  9. using System.Windows.Media;
  10. using System.Windows.Threading;
  11. using HandyControl.Data;
  12. using HandyControl.Interactivity;
  13. namespace HandyControl.Controls;
  14. /// <summary>
  15. /// 时间日期选择器
  16. /// </summary>
  17. [TemplatePart(Name = ElementRoot, Type = typeof(Grid))]
  18. [TemplatePart(Name = ElementTextBox, Type = typeof(WatermarkTextBox))]
  19. [TemplatePart(Name = ElementButton, Type = typeof(Button))]
  20. [TemplatePart(Name = ElementPopup, Type = typeof(Popup))]
  21. public class DateTimePicker : Control
  22. {
  23. #region Constants
  24. private const string ElementRoot = "PART_Root";
  25. private const string ElementTextBox = "PART_TextBox";
  26. private const string ElementButton = "PART_Button";
  27. private const string ElementPopup = "PART_Popup";
  28. #endregion Constants
  29. #region Data
  30. private CalendarWithClock _calendarWithClock;
  31. private string _defaultText;
  32. private ButtonBase _dropDownButton;
  33. private Popup _popup;
  34. private bool _disablePopupReopen;
  35. private WatermarkTextBox _textBox;
  36. private IDictionary<DependencyProperty, bool> _isHandlerSuspended;
  37. private DateTime? _originalSelectedDateTime;
  38. #endregion Data
  39. #region Public Events
  40. public static readonly RoutedEvent SelectedDateTimeChangedEvent =
  41. EventManager.RegisterRoutedEvent("SelectedDateTimeChanged", RoutingStrategy.Direct,
  42. typeof(EventHandler<FunctionEventArgs<DateTime?>>), typeof(DateTimePicker));
  43. public event EventHandler<FunctionEventArgs<DateTime?>> SelectedDateTimeChanged
  44. {
  45. add => AddHandler(SelectedDateTimeChangedEvent, value);
  46. remove => RemoveHandler(SelectedDateTimeChangedEvent, value);
  47. }
  48. public event RoutedEventHandler PickerClosed;
  49. public event RoutedEventHandler PickerOpened;
  50. #endregion Public Events
  51. static DateTimePicker()
  52. {
  53. EventManager.RegisterClassHandler(typeof(DateTimePicker), GotFocusEvent, new RoutedEventHandler(OnGotFocus));
  54. KeyboardNavigation.TabNavigationProperty.OverrideMetadata(typeof(DateTimePicker), new FrameworkPropertyMetadata(KeyboardNavigationMode.Once));
  55. KeyboardNavigation.IsTabStopProperty.OverrideMetadata(typeof(DateTimePicker), new FrameworkPropertyMetadata(ValueBoxes.FalseBox));
  56. }
  57. public DateTimePicker()
  58. {
  59. InitCalendarWithClock();
  60. CommandBindings.Add(new CommandBinding(ControlCommands.Clear, (s, e) =>
  61. {
  62. SetCurrentValue(SelectedDateTimeProperty, null);
  63. SetCurrentValue(TextProperty, "");
  64. _textBox.Text = string.Empty;
  65. }));
  66. }
  67. #region Public Properties
  68. public static readonly DependencyProperty DateTimeFormatProperty = DependencyProperty.Register(
  69. nameof(DateTimeFormat), typeof(string), typeof(DateTimePicker), new PropertyMetadata("yyyy-MM-dd HH:mm:ss"));
  70. public string DateTimeFormat
  71. {
  72. get => (string) GetValue(DateTimeFormatProperty);
  73. set => SetValue(DateTimeFormatProperty, value);
  74. }
  75. public static readonly DependencyProperty CalendarStyleProperty = DependencyProperty.Register(
  76. nameof(CalendarStyle), typeof(Style), typeof(DateTimePicker), new PropertyMetadata(default(Style)));
  77. public Style CalendarStyle
  78. {
  79. get => (Style) GetValue(CalendarStyleProperty);
  80. set => SetValue(CalendarStyleProperty, value);
  81. }
  82. public static readonly DependencyProperty DisplayDateTimeProperty = DependencyProperty.Register(
  83. nameof(DisplayDateTime), typeof(DateTime), typeof(DateTimePicker), new FrameworkPropertyMetadata(DateTime.Now, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, null, CoerceDisplayDateTime));
  84. private static object CoerceDisplayDateTime(DependencyObject d, object value)
  85. {
  86. var dp = (DateTimePicker) d;
  87. dp._calendarWithClock.DisplayDateTime = (DateTime) value;
  88. return dp._calendarWithClock.DisplayDateTime;
  89. }
  90. public DateTime DisplayDateTime
  91. {
  92. get => (DateTime) GetValue(DisplayDateTimeProperty);
  93. set => SetValue(DisplayDateTimeProperty, value);
  94. }
  95. public static readonly DependencyProperty IsDropDownOpenProperty = DependencyProperty.Register(
  96. nameof(IsDropDownOpen), typeof(bool), typeof(DateTimePicker), new FrameworkPropertyMetadata(ValueBoxes.FalseBox, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsDropDownOpenChanged, OnCoerceIsDropDownOpen));
  97. private static object OnCoerceIsDropDownOpen(DependencyObject d, object baseValue) =>
  98. d is DateTimePicker
  99. {
  100. IsEnabled: false
  101. }
  102. ? false
  103. : baseValue;
  104. private static void OnIsDropDownOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  105. {
  106. var dp = d as DateTimePicker;
  107. var newValue = (bool) e.NewValue;
  108. if (dp?._popup != null && dp._popup.IsOpen != newValue)
  109. {
  110. dp._popup.IsOpen = newValue;
  111. if (newValue)
  112. {
  113. dp._originalSelectedDateTime = dp.SelectedDateTime;
  114. dp.Dispatcher.BeginInvoke(DispatcherPriority.Input, (Action) delegate
  115. {
  116. dp._calendarWithClock.Focus();
  117. });
  118. }
  119. }
  120. }
  121. public bool IsDropDownOpen
  122. {
  123. get => (bool) GetValue(IsDropDownOpenProperty);
  124. set => SetValue(IsDropDownOpenProperty, ValueBoxes.BooleanBox(value));
  125. }
  126. public static readonly DependencyProperty SelectedDateTimeProperty = DependencyProperty.Register(
  127. nameof(SelectedDateTime), typeof(DateTime?), typeof(DateTimePicker), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedDateTimeChanged, CoerceSelectedDateTime));
  128. private static object CoerceSelectedDateTime(DependencyObject d, object value)
  129. {
  130. var dp = (DateTimePicker) d;
  131. dp._calendarWithClock.SelectedDateTime = (DateTime?) value;
  132. return dp._calendarWithClock.SelectedDateTime;
  133. }
  134. private static void OnSelectedDateTimeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  135. {
  136. if (d is not DateTimePicker dp) return;
  137. if (dp.SelectedDateTime.HasValue)
  138. {
  139. var time = dp.SelectedDateTime.Value;
  140. dp.SetTextInternal(dp.DateTimeToString(time));
  141. }
  142. dp.RaiseEvent(new FunctionEventArgs<DateTime?>(SelectedDateTimeChangedEvent, dp)
  143. {
  144. Info = dp.SelectedDateTime
  145. });
  146. }
  147. public DateTime? SelectedDateTime
  148. {
  149. get => (DateTime?) GetValue(SelectedDateTimeProperty);
  150. set => SetValue(SelectedDateTimeProperty, value);
  151. }
  152. public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
  153. nameof(Text), typeof(string), typeof(DateTimePicker), new FrameworkPropertyMetadata(string.Empty, OnTextChanged));
  154. private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  155. {
  156. if (d is DateTimePicker dp && !dp.IsHandlerSuspended(TextProperty))
  157. {
  158. if (e.NewValue is string newValue)
  159. {
  160. if (dp._textBox != null)
  161. {
  162. dp._textBox.Text = newValue;
  163. }
  164. else
  165. {
  166. dp._defaultText = newValue;
  167. }
  168. dp.SetSelectedDateTime();
  169. }
  170. else
  171. {
  172. dp.SetValueNoCallback(SelectedDateTimeProperty, null);
  173. }
  174. }
  175. }
  176. public string Text
  177. {
  178. get => (string) GetValue(TextProperty);
  179. set => SetValue(TextProperty, value);
  180. }
  181. /// <summary>
  182. /// Sets the local Text property without breaking bindings
  183. /// </summary>
  184. /// <param name="value"></param>
  185. private void SetTextInternal(string value)
  186. {
  187. SetCurrentValue(TextProperty, value);
  188. }
  189. public static readonly DependencyProperty SelectionBrushProperty =
  190. TextBoxBase.SelectionBrushProperty.AddOwner(typeof(DateTimePicker));
  191. public Brush SelectionBrush
  192. {
  193. get => (Brush) GetValue(SelectionBrushProperty);
  194. set => SetValue(SelectionBrushProperty, value);
  195. }
  196. #if !(NET40 || NET45 || NET451 || NET452 || NET46 || NET461 || NET462 || NET47 || NET471 || NET472)
  197. public static readonly DependencyProperty SelectionTextBrushProperty =
  198. TextBoxBase.SelectionTextBrushProperty.AddOwner(typeof(DateTimePicker));
  199. public Brush SelectionTextBrush
  200. {
  201. get => (Brush) GetValue(SelectionTextBrushProperty);
  202. set => SetValue(SelectionTextBrushProperty, value);
  203. }
  204. #endif
  205. public static readonly DependencyProperty SelectionOpacityProperty =
  206. TextBoxBase.SelectionOpacityProperty.AddOwner(typeof(DateTimePicker));
  207. public double SelectionOpacity
  208. {
  209. get => (double) GetValue(SelectionOpacityProperty);
  210. set => SetValue(SelectionOpacityProperty, value);
  211. }
  212. public static readonly DependencyProperty CaretBrushProperty =
  213. TextBoxBase.CaretBrushProperty.AddOwner(typeof(DateTimePicker));
  214. public Brush CaretBrush
  215. {
  216. get => (Brush) GetValue(CaretBrushProperty);
  217. set => SetValue(CaretBrushProperty, value);
  218. }
  219. #endregion
  220. #region Public Methods
  221. public override void OnApplyTemplate()
  222. {
  223. if (DesignerProperties.GetIsInDesignMode(this)) return;
  224. if (_popup != null)
  225. {
  226. _popup.PreviewMouseLeftButtonDown -= PopupPreviewMouseLeftButtonDown;
  227. _popup.Opened -= PopupOpened;
  228. _popup.Closed -= PopupClosed;
  229. _popup.Child = null;
  230. }
  231. if (_dropDownButton != null)
  232. {
  233. _dropDownButton.Click -= DropDownButton_Click;
  234. _dropDownButton.MouseLeave -= DropDownButton_MouseLeave;
  235. }
  236. if (_textBox != null)
  237. {
  238. _textBox.KeyDown -= TextBox_KeyDown;
  239. _textBox.TextChanged -= TextBox_TextChanged;
  240. _textBox.LostFocus -= TextBox_LostFocus;
  241. }
  242. base.OnApplyTemplate();
  243. _popup = GetTemplateChild(ElementPopup) as Popup;
  244. _dropDownButton = GetTemplateChild(ElementButton) as Button;
  245. _textBox = GetTemplateChild(ElementTextBox) as WatermarkTextBox;
  246. CheckNull();
  247. _popup.PreviewMouseLeftButtonDown += PopupPreviewMouseLeftButtonDown;
  248. _popup.Opened += PopupOpened;
  249. _popup.Closed += PopupClosed;
  250. _popup.Child = _calendarWithClock;
  251. _dropDownButton.Click += DropDownButton_Click;
  252. _dropDownButton.MouseLeave += DropDownButton_MouseLeave;
  253. var selectedDateTime = SelectedDateTime;
  254. if (_textBox != null)
  255. {
  256. _textBox.SetBinding(SelectionBrushProperty, new Binding(SelectionBrushProperty.Name) { Source = this });
  257. #if !(NET40 || NET45 || NET451 || NET452 || NET46 || NET461 || NET462 || NET47 || NET471 || NET472)
  258. _textBox.SetBinding(SelectionTextBrushProperty, new Binding(SelectionTextBrushProperty.Name) { Source = this });
  259. #endif
  260. _textBox.SetBinding(SelectionOpacityProperty, new Binding(SelectionOpacityProperty.Name) { Source = this });
  261. _textBox.SetBinding(CaretBrushProperty, new Binding(CaretBrushProperty.Name) { Source = this });
  262. _textBox.KeyDown += TextBox_KeyDown;
  263. _textBox.TextChanged += TextBox_TextChanged;
  264. _textBox.LostFocus += TextBox_LostFocus;
  265. if (selectedDateTime == null)
  266. {
  267. if (!string.IsNullOrEmpty(_defaultText))
  268. {
  269. _textBox.Text = _defaultText;
  270. SetSelectedDateTime();
  271. }
  272. }
  273. else
  274. {
  275. _textBox.Text = DateTimeToString(selectedDateTime.Value);
  276. }
  277. }
  278. if (selectedDateTime is null)
  279. {
  280. _originalSelectedDateTime ??= DateTime.Now;
  281. SetCurrentValue(DisplayDateTimeProperty, _originalSelectedDateTime);
  282. }
  283. else
  284. {
  285. SetCurrentValue(DisplayDateTimeProperty, selectedDateTime);
  286. }
  287. }
  288. public override string ToString() => SelectedDateTime?.ToString(DateTimeFormat) ?? string.Empty;
  289. #endregion
  290. #region Protected Methods
  291. protected virtual void OnPickerClosed(RoutedEventArgs e)
  292. {
  293. var handler = PickerClosed;
  294. handler?.Invoke(this, e);
  295. }
  296. protected virtual void OnPickerOpened(RoutedEventArgs e)
  297. {
  298. var handler = PickerOpened;
  299. handler?.Invoke(this, e);
  300. }
  301. #endregion Protected Methods
  302. #region Private Methods
  303. private void CheckNull()
  304. {
  305. if (_dropDownButton == null || _popup == null || _textBox == null)
  306. throw new Exception();
  307. }
  308. private void InitCalendarWithClock()
  309. {
  310. _calendarWithClock = new CalendarWithClock
  311. {
  312. ShowConfirmButton = true
  313. };
  314. _calendarWithClock.SelectedDateTimeChanged += CalendarWithClock_SelectedDateTimeChanged;
  315. _calendarWithClock.Confirmed += CalendarWithClock_Confirmed;
  316. }
  317. private void CalendarWithClock_Confirmed() => TogglePopup();
  318. private void CalendarWithClock_SelectedDateTimeChanged(object sender, FunctionEventArgs<DateTime?> e) => SelectedDateTime = e.Info;
  319. private void TextBox_LostFocus(object sender, RoutedEventArgs e)
  320. {
  321. SetSelectedDateTime();
  322. }
  323. private void SetIsHandlerSuspended(DependencyProperty property, bool value)
  324. {
  325. if (value)
  326. {
  327. _isHandlerSuspended ??= new Dictionary<DependencyProperty, bool>(2);
  328. _isHandlerSuspended[property] = true;
  329. }
  330. else
  331. {
  332. _isHandlerSuspended?.Remove(property);
  333. }
  334. }
  335. private void SetValueNoCallback(DependencyProperty property, object value)
  336. {
  337. SetIsHandlerSuspended(property, true);
  338. try
  339. {
  340. SetCurrentValue(property, value);
  341. }
  342. finally
  343. {
  344. SetIsHandlerSuspended(property, false);
  345. }
  346. }
  347. private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
  348. {
  349. SetValueNoCallback(TextProperty, _textBox.Text);
  350. }
  351. private bool ProcessDateTimePickerKey(KeyEventArgs e)
  352. {
  353. switch (e.Key)
  354. {
  355. case Key.System:
  356. {
  357. switch (e.SystemKey)
  358. {
  359. case Key.Down:
  360. {
  361. if ((Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt)
  362. {
  363. TogglePopup();
  364. return true;
  365. }
  366. break;
  367. }
  368. }
  369. break;
  370. }
  371. case Key.Enter:
  372. {
  373. SetSelectedDateTime();
  374. return true;
  375. }
  376. }
  377. return false;
  378. }
  379. private void TextBox_KeyDown(object sender, KeyEventArgs e)
  380. {
  381. e.Handled = ProcessDateTimePickerKey(e) || e.Handled;
  382. }
  383. private void DropDownButton_MouseLeave(object sender, MouseEventArgs e)
  384. {
  385. _disablePopupReopen = false;
  386. }
  387. private bool IsHandlerSuspended(DependencyProperty property)
  388. {
  389. return _isHandlerSuspended != null && _isHandlerSuspended.ContainsKey(property);
  390. }
  391. private void PopupPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  392. {
  393. if (sender is Popup { StaysOpen: false })
  394. {
  395. if (_dropDownButton?.InputHitTest(e.GetPosition(_dropDownButton)) != null)
  396. {
  397. _disablePopupReopen = true;
  398. }
  399. }
  400. }
  401. private void PopupOpened(object sender, EventArgs e)
  402. {
  403. if (!IsDropDownOpen)
  404. {
  405. SetCurrentValue(IsDropDownOpenProperty, ValueBoxes.TrueBox);
  406. }
  407. _calendarWithClock?.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
  408. OnPickerOpened(new RoutedEventArgs());
  409. }
  410. private void PopupClosed(object sender, EventArgs e)
  411. {
  412. if (IsDropDownOpen)
  413. {
  414. SetCurrentValue(IsDropDownOpenProperty, ValueBoxes.FalseBox);
  415. }
  416. if (_calendarWithClock.IsKeyboardFocusWithin)
  417. {
  418. MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
  419. }
  420. OnPickerClosed(new RoutedEventArgs());
  421. }
  422. private void DropDownButton_Click(object sender, RoutedEventArgs e) => TogglePopup();
  423. private void TogglePopup()
  424. {
  425. if (IsDropDownOpen)
  426. {
  427. SetCurrentValue(IsDropDownOpenProperty, ValueBoxes.FalseBox);
  428. }
  429. else
  430. {
  431. if (_disablePopupReopen)
  432. {
  433. _disablePopupReopen = false;
  434. }
  435. else
  436. {
  437. SetSelectedDateTime();
  438. SetCurrentValue(IsDropDownOpenProperty, ValueBoxes.TrueBox);
  439. }
  440. }
  441. }
  442. private void SafeSetText(string s)
  443. {
  444. if (string.Compare(Text, s, StringComparison.Ordinal) != 0)
  445. {
  446. SetCurrentValue(TextProperty, s);
  447. }
  448. }
  449. private DateTime? ParseText(string text)
  450. {
  451. try
  452. {
  453. return DateTime.Parse(text);
  454. }
  455. catch
  456. {
  457. // ignored
  458. }
  459. return null;
  460. }
  461. private DateTime? SetTextBoxValue(string s)
  462. {
  463. if (string.IsNullOrEmpty(s))
  464. {
  465. SafeSetText(s);
  466. return SelectedDateTime;
  467. }
  468. var d = ParseText(s);
  469. if (d != null)
  470. {
  471. SafeSetText(DateTimeToString((DateTime) d));
  472. return d;
  473. }
  474. if (SelectedDateTime != null)
  475. {
  476. var newtext = DateTimeToString(SelectedDateTime.Value);
  477. SafeSetText(newtext);
  478. return SelectedDateTime;
  479. }
  480. SafeSetText(DateTimeToString(DisplayDateTime));
  481. return DisplayDateTime;
  482. }
  483. private void SetSelectedDateTime()
  484. {
  485. if (_textBox != null)
  486. {
  487. if (!string.IsNullOrEmpty(_textBox.Text))
  488. {
  489. var s = _textBox.Text;
  490. if (SelectedDateTime != null)
  491. {
  492. if (SelectedDateTime != DisplayDateTime)
  493. {
  494. SetCurrentValue(DisplayDateTimeProperty, SelectedDateTime);
  495. }
  496. var selectedTime = DateTimeToString(SelectedDateTime.Value);
  497. if (string.Compare(selectedTime, s, StringComparison.Ordinal) == 0)
  498. {
  499. return;
  500. }
  501. }
  502. var d = SetTextBoxValue(s);
  503. if (!SelectedDateTime.Equals(d))
  504. {
  505. SetCurrentValue(SelectedDateTimeProperty, d);
  506. SetCurrentValue(DisplayDateTimeProperty, d);
  507. }
  508. }
  509. else
  510. {
  511. if (SelectedDateTime.HasValue)
  512. {
  513. SetCurrentValue(SelectedDateTimeProperty, null);
  514. }
  515. }
  516. }
  517. else
  518. {
  519. var d = SetTextBoxValue(_defaultText);
  520. if (!SelectedDateTime.Equals(d))
  521. {
  522. SetCurrentValue(SelectedDateTimeProperty, d);
  523. }
  524. }
  525. }
  526. private string DateTimeToString(DateTime d) => d.ToString(DateTimeFormat);
  527. private static void OnGotFocus(object sender, RoutedEventArgs e)
  528. {
  529. var picker = (DateTimePicker) sender;
  530. if (!e.Handled && picker._textBox != null)
  531. {
  532. if (Equals(e.OriginalSource, picker))
  533. {
  534. picker._textBox.Focus();
  535. e.Handled = true;
  536. }
  537. else if (Equals(e.OriginalSource, picker._textBox))
  538. {
  539. picker._textBox.SelectAll();
  540. e.Handled = true;
  541. }
  542. }
  543. }
  544. #endregion
  545. }