DatePicker.cs 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  1. // (c) Copyright Microsoft Corporation.
  2. // This source is subject to the Microsoft Public License (Ms-PL).
  3. // Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
  4. // All other rights reserved.
  5. using System;
  6. using System.Collections.ObjectModel;
  7. using System.Diagnostics;
  8. using System.Globalization;
  9. using Avalonia.Controls.Primitives;
  10. using Avalonia.Data;
  11. using Avalonia.Input;
  12. using Avalonia.Interactivity;
  13. namespace Avalonia.Controls
  14. {
  15. /// <summary>
  16. /// Provides data for the
  17. /// <see cref="E:Avalonia.Controls.DatePicker.DateValidationError" />
  18. /// event.
  19. /// </summary>
  20. public class DatePickerDateValidationErrorEventArgs : EventArgs
  21. {
  22. private bool _throwException;
  23. /// <summary>
  24. /// Initializes a new instance of the
  25. /// <see cref="T:Avalonia.Controls.DatePickerDateValidationErrorEventArgs" />
  26. /// class.
  27. /// </summary>
  28. /// <param name="exception">
  29. /// The initial exception from the
  30. /// <see cref="E:Avalonia.Controls.DatePicker.DateValidationError" />
  31. /// event.
  32. /// </param>
  33. /// <param name="text">
  34. /// The text that caused the
  35. /// <see cref="E:Avalonia.Controls.DatePicker.DateValidationError" />
  36. /// event.
  37. /// </param>
  38. public DatePickerDateValidationErrorEventArgs(Exception exception, string text)
  39. {
  40. this.Text = text;
  41. this.Exception = exception;
  42. }
  43. /// <summary>
  44. /// Gets the initial exception associated with the
  45. /// <see cref="E:Avalonia.Controls.DatePicker.DateValidationError" />
  46. /// event.
  47. /// </summary>
  48. /// <value>
  49. /// The exception associated with the validation failure.
  50. /// </value>
  51. public Exception Exception { get; private set; }
  52. /// <summary>
  53. /// Gets the text that caused the
  54. /// <see cref="E:Avalonia.Controls.DatePicker.DateValidationError" />
  55. /// event.
  56. /// </summary>
  57. /// <value>
  58. /// The text that caused the validation failure.
  59. /// </value>
  60. public string Text { get; private set; }
  61. /// <summary>
  62. /// Gets or sets a value indicating whether
  63. /// <see cref="P:Avalonia.Controls.DatePickerDateValidationErrorEventArgs.Exception" />
  64. /// should be thrown.
  65. /// </summary>
  66. /// <value>
  67. /// True if the exception should be thrown; otherwise, false.
  68. /// </value>
  69. /// <exception cref="T:System.ArgumentException">
  70. /// If set to true and
  71. /// <see cref="P:Avalonia.Controls.DatePickerDateValidationErrorEventArgs.Exception" />
  72. /// is null.
  73. /// </exception>
  74. public bool ThrowException
  75. {
  76. get { return this._throwException; }
  77. set
  78. {
  79. if (value && this.Exception == null)
  80. {
  81. throw new ArgumentException("Cannot Throw Null Exception");
  82. }
  83. this._throwException = value;
  84. }
  85. }
  86. }
  87. /// <summary>
  88. /// Specifies date formats for a
  89. /// <see cref="T:Avalonia.Controls.DatePicker" />.
  90. /// </summary>
  91. public enum DatePickerFormat
  92. {
  93. /// <summary>
  94. /// Specifies that the date should be displayed using unabbreviated days
  95. /// of the week and month names.
  96. /// </summary>
  97. Long = 0,
  98. /// <summary>
  99. /// Specifies that the date should be displayed using abbreviated days
  100. /// of the week and month names.
  101. /// </summary>
  102. Short = 1,
  103. /// <summary>
  104. /// Specifies that the date should be displayed using a custom format string.
  105. /// </summary>
  106. Custom = 2
  107. }
  108. public class DatePicker : TemplatedControl
  109. {
  110. private const string ElementTextBox = "PART_TextBox";
  111. private const string ElementButton = "PART_Button";
  112. private const string ElementPopup = "PART_Popup";
  113. private const string ElementCalendar = "PART_Calendar";
  114. private Calendar _calendar;
  115. private string _defaultText;
  116. private Button _dropDownButton;
  117. //private Canvas _outsideCanvas;
  118. //private Canvas _outsidePopupCanvas;
  119. private Popup _popUp;
  120. private TextBox _textBox;
  121. private IDisposable _textBoxTextChangedSubscription;
  122. private IDisposable _buttonPointerPressedSubscription;
  123. private DateTime? _onOpenSelectedDate;
  124. private bool _settingSelectedDate;
  125. private DateTime _displayDate;
  126. private DateTime? _displayDateStart;
  127. private DateTime? _displayDateEnd;
  128. private bool _isDropDownOpen;
  129. private DateTime? _selectedDate;
  130. private string _text;
  131. private bool _suspendTextChangeHandler = false;
  132. private bool _isPopupClosing = false;
  133. private bool _ignoreButtonClick = false;
  134. /// <summary>
  135. /// Gets a collection of dates that are marked as not selectable.
  136. /// </summary>
  137. /// <value>
  138. /// A collection of dates that cannot be selected. The default value is
  139. /// an empty collection.
  140. /// </value>
  141. public CalendarBlackoutDatesCollection BlackoutDates { get; private set; }
  142. public static readonly DirectProperty<DatePicker, DateTime> DisplayDateProperty =
  143. AvaloniaProperty.RegisterDirect<DatePicker, DateTime>(
  144. nameof(DisplayDate),
  145. o => o.DisplayDate,
  146. (o, v) => o.DisplayDate = v);
  147. public static readonly DirectProperty<DatePicker, DateTime?> DisplayDateStartProperty =
  148. AvaloniaProperty.RegisterDirect<DatePicker, DateTime?>(
  149. nameof(DisplayDateStart),
  150. o => o.DisplayDateStart,
  151. (o, v) => o.DisplayDateStart = v);
  152. public static readonly DirectProperty<DatePicker, DateTime?> DisplayDateEndProperty =
  153. AvaloniaProperty.RegisterDirect<DatePicker, DateTime?>(
  154. nameof(DisplayDateEnd),
  155. o => o.DisplayDateEnd,
  156. (o, v) => o.DisplayDateEnd = v);
  157. public static readonly StyledProperty<DayOfWeek> FirstDayOfWeekProperty =
  158. AvaloniaProperty.Register<DatePicker, DayOfWeek>(nameof(FirstDayOfWeek));
  159. public static readonly DirectProperty<DatePicker, bool> IsDropDownOpenProperty =
  160. AvaloniaProperty.RegisterDirect<DatePicker, bool>(
  161. nameof(IsDropDownOpen),
  162. o => o.IsDropDownOpen,
  163. (o, v) => o.IsDropDownOpen = v);
  164. public static readonly StyledProperty<bool> IsTodayHighlightedProperty =
  165. AvaloniaProperty.Register<DatePicker, bool>(nameof(IsTodayHighlighted));
  166. public static readonly DirectProperty<DatePicker, DateTime?> SelectedDateProperty =
  167. AvaloniaProperty.RegisterDirect<DatePicker, DateTime?>(
  168. nameof(SelectedDate),
  169. o => o.SelectedDate,
  170. (o, v) => o.SelectedDate = v);
  171. public static readonly StyledProperty<DatePickerFormat> SelectedDateFormatProperty =
  172. AvaloniaProperty.Register<DatePicker, DatePickerFormat>(
  173. nameof(SelectedDateFormat),
  174. defaultValue: DatePickerFormat.Short,
  175. validate: ValidateSelectedDateFormat);
  176. public static readonly StyledProperty<string> CustomDateFormatStringProperty =
  177. AvaloniaProperty.Register<DatePicker, string>(
  178. nameof(CustomDateFormatString),
  179. defaultValue: "d",
  180. validate: ValidateDateFormatString);
  181. public static readonly DirectProperty<DatePicker, string> TextProperty =
  182. AvaloniaProperty.RegisterDirect<DatePicker, string>(
  183. nameof(Text),
  184. o => o.Text,
  185. (o, v) => o.Text = v);
  186. public static readonly StyledProperty<string> WatermarkProperty =
  187. TextBox.WatermarkProperty.AddOwner<DatePicker>();
  188. public static readonly StyledProperty<bool> UseFloatingWatermarkProperty =
  189. TextBox.UseFloatingWatermarkProperty.AddOwner<DatePicker>();
  190. /// <summary>
  191. /// Gets or sets the date to display.
  192. /// </summary>
  193. /// <value>
  194. /// The date to display. The default
  195. /// <see cref="P:System.DateTime.Today" />.
  196. /// </value>
  197. /// <exception cref="T:System.ArgumentOutOfRangeException">
  198. /// The specified date is not in the range defined by
  199. /// <see cref="P:Avalonia.Controls.DatePicker.DisplayDateStart" />
  200. /// and
  201. /// <see cref="P:Avalonia.Controls.DatePicker.DisplayDateEnd" />.
  202. /// </exception>
  203. public DateTime DisplayDate
  204. {
  205. get { return _displayDate; }
  206. set { SetAndRaise(DisplayDateProperty, ref _displayDate, value); }
  207. }
  208. /// <summary>
  209. /// Gets or sets the first date to be displayed.
  210. /// </summary>
  211. /// <value>The first date to display.</value>
  212. public DateTime? DisplayDateStart
  213. {
  214. get { return _displayDateStart; }
  215. set { SetAndRaise(DisplayDateStartProperty, ref _displayDateStart, value); }
  216. }
  217. /// <summary>
  218. /// Gets or sets the last date to be displayed.
  219. /// </summary>
  220. /// <value>The last date to display.</value>
  221. public DateTime? DisplayDateEnd
  222. {
  223. get { return _displayDateEnd; }
  224. set { SetAndRaise(DisplayDateEndProperty, ref _displayDateEnd, value); }
  225. }
  226. /// <summary>
  227. /// Gets or sets the day that is considered the beginning of the week.
  228. /// </summary>
  229. /// <value>
  230. /// A <see cref="T:System.DayOfWeek" /> representing the beginning of
  231. /// the week. The default is <see cref="F:System.DayOfWeek.Sunday" />.
  232. /// </value>
  233. public DayOfWeek FirstDayOfWeek
  234. {
  235. get { return GetValue(FirstDayOfWeekProperty); }
  236. set { SetValue(FirstDayOfWeekProperty, value); }
  237. }
  238. /// <summary>
  239. /// Gets or sets a value indicating whether the drop-down
  240. /// <see cref="T:Avalonia.Controls.Calendar" /> is open or closed.
  241. /// </summary>
  242. /// <value>
  243. /// True if the <see cref="T:Avalonia.Controls.Calendar" /> is
  244. /// open; otherwise, false. The default is false.
  245. /// </value>
  246. public bool IsDropDownOpen
  247. {
  248. get { return _isDropDownOpen; }
  249. set { SetAndRaise(IsDropDownOpenProperty, ref _isDropDownOpen, value); }
  250. }
  251. /// <summary>
  252. /// Gets or sets a value indicating whether the current date will be
  253. /// highlighted.
  254. /// </summary>
  255. /// <value>
  256. /// True if the current date is highlighted; otherwise, false. The
  257. /// default is true.
  258. /// </value>
  259. public bool IsTodayHighlighted
  260. {
  261. get { return GetValue(IsTodayHighlightedProperty); }
  262. set { SetValue(IsTodayHighlightedProperty, value); }
  263. }
  264. /// <summary>
  265. /// Gets or sets the currently selected date.
  266. /// </summary>
  267. /// <value>
  268. /// The date currently selected. The default is null.
  269. /// </value>
  270. /// <exception cref="T:System.ArgumentOutOfRangeException">
  271. /// The specified date is not in the range defined by
  272. /// <see cref="P:Avalonia.Controls.DatePicker.DisplayDateStart" />
  273. /// and
  274. /// <see cref="P:Avalonia.Controls.DatePicker.DisplayDateEnd" />,
  275. /// or the specified date is in the
  276. /// <see cref="P:Avalonia.Controls.DatePicker.BlackoutDates" />
  277. /// collection.
  278. /// </exception>
  279. public DateTime? SelectedDate
  280. {
  281. get { return _selectedDate; }
  282. set { SetAndRaise(SelectedDateProperty, ref _selectedDate, value); }
  283. }
  284. /// <summary>
  285. /// Gets or sets the format that is used to display the selected date.
  286. /// </summary>
  287. /// <value>
  288. /// The format that is used to display the selected date. The default is
  289. /// <see cref="F:Avalonia.Controls.DatePickerFormat.Short" />.
  290. /// </value>
  291. /// <exception cref="T:System.ArgumentOutOfRangeException">
  292. /// An specified format is not valid.
  293. /// </exception>
  294. public DatePickerFormat SelectedDateFormat
  295. {
  296. get { return GetValue(SelectedDateFormatProperty); }
  297. set { SetValue(SelectedDateFormatProperty, value); }
  298. }
  299. public string CustomDateFormatString
  300. {
  301. get { return GetValue(CustomDateFormatStringProperty); }
  302. set { SetValue(CustomDateFormatStringProperty, value); }
  303. }
  304. /// <summary>
  305. /// Gets or sets the text that is displayed by the
  306. /// <see cref="T:Avalonia.Controls.DatePicker" />.
  307. /// </summary>
  308. /// <value>
  309. /// The text displayed by the
  310. /// <see cref="T:Avalonia.Controls.DatePicker" />.
  311. /// </value>
  312. /// <exception cref="T:System.FormatException">
  313. /// The text entered cannot be parsed to a valid date, and the exception
  314. /// is not suppressed.
  315. /// </exception>
  316. /// <exception cref="T:System.ArgumentOutOfRangeException">
  317. /// The text entered parses to a date that is not selectable.
  318. /// </exception>
  319. public string Text
  320. {
  321. get { return _text; }
  322. set { SetAndRaise(TextProperty, ref _text, value); }
  323. }
  324. public string Watermark
  325. {
  326. get { return GetValue(WatermarkProperty); }
  327. set { SetValue(WatermarkProperty, value); }
  328. }
  329. public bool UseFloatingWatermark
  330. {
  331. get { return GetValue(UseFloatingWatermarkProperty); }
  332. set { SetValue(UseFloatingWatermarkProperty, value); }
  333. }
  334. /// <summary>
  335. /// Occurs when the drop-down
  336. /// <see cref="T:Avalonia.Controls.Calendar" /> is closed.
  337. /// </summary>
  338. public event EventHandler CalendarClosed;
  339. /// <summary>
  340. /// Occurs when the drop-down
  341. /// <see cref="T:Avalonia.Controls.Calendar" /> is opened.
  342. /// </summary>
  343. public event EventHandler CalendarOpened;
  344. /// <summary>
  345. /// Occurs when <see cref="P:Avalonia.Controls.DatePicker.Text" />
  346. /// is assigned a value that cannot be interpreted as a date.
  347. /// </summary>
  348. public event EventHandler<DatePickerDateValidationErrorEventArgs> DateValidationError;
  349. /// <summary>
  350. /// Occurs when the
  351. /// <see cref="P:Avalonia.Controls.DatePicker.SelectedDate" />
  352. /// property is changed.
  353. /// </summary>
  354. public event EventHandler<SelectionChangedEventArgs> SelectedDateChanged;
  355. static DatePicker()
  356. {
  357. FocusableProperty.OverrideDefaultValue<DatePicker>(true);
  358. DisplayDateProperty.Changed.AddClassHandler<DatePicker>(x => x.OnDisplayDateChanged);
  359. DisplayDateStartProperty.Changed.AddClassHandler<DatePicker>(x => x.OnDisplayDateStartChanged);
  360. DisplayDateEndProperty.Changed.AddClassHandler<DatePicker>(x => x.OnDisplayDateEndChanged);
  361. IsDropDownOpenProperty.Changed.AddClassHandler<DatePicker>(x => x.OnIsDropDownOpenChanged);
  362. SelectedDateProperty.Changed.AddClassHandler<DatePicker>(x => x.OnSelectedDateChanged);
  363. SelectedDateFormatProperty.Changed.AddClassHandler<DatePicker>(x => x.OnSelectedDateFormatChanged);
  364. CustomDateFormatStringProperty.Changed.AddClassHandler<DatePicker>(x => x.OnCustomDateFormatStringChanged);
  365. TextProperty.Changed.AddClassHandler<DatePicker>(x => x.OnTextChanged);
  366. }
  367. /// <summary>
  368. /// Initializes a new instance of the
  369. /// <see cref="T:Avalonia.Controls.DatePicker" /> class.
  370. /// </summary>
  371. public DatePicker()
  372. {
  373. FirstDayOfWeek = DateTimeHelper.GetCurrentDateFormat().FirstDayOfWeek;
  374. _defaultText = string.Empty;
  375. DisplayDate = DateTime.Today;
  376. }
  377. protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
  378. {
  379. if (_calendar != null)
  380. {
  381. _calendar.DayButtonMouseUp -= Calendar_DayButtonMouseUp;
  382. _calendar.DisplayDateChanged -= Calendar_DisplayDateChanged;
  383. _calendar.SelectedDatesChanged -= Calendar_SelectedDatesChanged;
  384. _calendar.PointerPressed -= Calendar_PointerPressed;
  385. _calendar.KeyDown -= Calendar_KeyDown;
  386. }
  387. _calendar = e.NameScope.Find<Calendar>(ElementCalendar);
  388. if (_calendar != null)
  389. {
  390. _calendar.SelectionMode = CalendarSelectionMode.SingleDate;
  391. _calendar.SelectedDate = SelectedDate;
  392. SetCalendarDisplayDate(DisplayDate);
  393. SetCalendarDisplayDateStart(DisplayDateStart);
  394. SetCalendarDisplayDateEnd(DisplayDateEnd);
  395. _calendar.DayButtonMouseUp += Calendar_DayButtonMouseUp;
  396. _calendar.DisplayDateChanged += Calendar_DisplayDateChanged;
  397. _calendar.SelectedDatesChanged += Calendar_SelectedDatesChanged;
  398. _calendar.PointerPressed += Calendar_PointerPressed;
  399. _calendar.KeyDown += Calendar_KeyDown;
  400. //_calendar.SizeChanged += new SizeChangedEventHandler(Calendar_SizeChanged);
  401. //_calendar.IsTabStop = true;
  402. var currentBlackoutDays = BlackoutDates;
  403. BlackoutDates = _calendar.BlackoutDates;
  404. if(currentBlackoutDays != null)
  405. {
  406. foreach (var range in currentBlackoutDays)
  407. {
  408. BlackoutDates.Add(range);
  409. }
  410. }
  411. }
  412. if (_popUp != null)
  413. {
  414. _popUp.Child = null;
  415. _popUp.Closed -= PopUp_Closed;
  416. }
  417. _popUp = e.NameScope.Find<Popup>(ElementPopup);
  418. if(_popUp != null)
  419. {
  420. _popUp.Closed += PopUp_Closed;
  421. if (IsDropDownOpen)
  422. {
  423. OpenDropDown();
  424. }
  425. }
  426. if(_dropDownButton != null)
  427. {
  428. _dropDownButton.Click -= DropDownButton_Click;
  429. _buttonPointerPressedSubscription?.Dispose();
  430. }
  431. _dropDownButton = e.NameScope.Find<Button>(ElementButton);
  432. if(_dropDownButton != null)
  433. {
  434. _dropDownButton.Click += DropDownButton_Click;
  435. _buttonPointerPressedSubscription =
  436. _dropDownButton.AddHandler(PointerPressedEvent, DropDownButton_PointerPressed, handledEventsToo: true);
  437. }
  438. if (_textBox != null)
  439. {
  440. _textBox.KeyDown -= TextBox_KeyDown;
  441. _textBox.GotFocus -= TextBox_GotFocus;
  442. _textBoxTextChangedSubscription?.Dispose();
  443. }
  444. _textBox = e.NameScope.Find<TextBox>(ElementTextBox);
  445. if(!SelectedDate.HasValue)
  446. {
  447. SetWaterMarkText();
  448. }
  449. if(_textBox != null)
  450. {
  451. _textBox.KeyDown += TextBox_KeyDown;
  452. _textBox.GotFocus += TextBox_GotFocus;
  453. _textBoxTextChangedSubscription = _textBox.GetObservable(TextBox.TextProperty).Subscribe(txt => TextBox_TextChanged());
  454. if(SelectedDate.HasValue)
  455. {
  456. _textBox.Text = DateTimeToString(SelectedDate.Value);
  457. }
  458. else if(!String.IsNullOrEmpty(_defaultText))
  459. {
  460. _textBox.Text = _defaultText;
  461. SetSelectedDate();
  462. }
  463. }
  464. base.OnTemplateApplied(e);
  465. }
  466. protected override void UpdateDataValidation(AvaloniaProperty property, BindingNotification status)
  467. {
  468. if (property == SelectedDateProperty)
  469. {
  470. DataValidationErrors.SetError(this, status.Error);
  471. }
  472. }
  473. protected override void OnPointerWheelChanged(PointerWheelEventArgs e)
  474. {
  475. base.OnPointerWheelChanged(e);
  476. if (!e.Handled && SelectedDate.HasValue && _calendar != null)
  477. {
  478. DateTime selectedDate = this.SelectedDate.Value;
  479. DateTime? newDate = DateTimeHelper.AddDays(selectedDate, e.Delta.Y > 0 ? -1 : 1);
  480. if (newDate.HasValue && Calendar.IsValidDateSelection(_calendar, newDate.Value))
  481. {
  482. SelectedDate = newDate;
  483. e.Handled = true;
  484. }
  485. }
  486. }
  487. protected override void OnGotFocus(GotFocusEventArgs e)
  488. {
  489. base.OnGotFocus(e);
  490. if(IsEnabled && _textBox != null && e.NavigationMethod == NavigationMethod.Tab)
  491. {
  492. _textBox.Focus();
  493. var text = _textBox.Text;
  494. if(!string.IsNullOrEmpty(text))
  495. {
  496. _textBox.SelectionStart = 0;
  497. _textBox.SelectionEnd = text.Length;
  498. }
  499. }
  500. }
  501. protected override void OnLostFocus(RoutedEventArgs e)
  502. {
  503. base.OnLostFocus(e);
  504. SetSelectedDate();
  505. }
  506. private void SetCalendarDisplayDate(DateTime value)
  507. {
  508. if (DateTimeHelper.CompareYearMonth(_calendar.DisplayDate, value) != 0)
  509. {
  510. _calendar.DisplayDate = DisplayDate;
  511. if (DateTime.Compare(_calendar.DisplayDate, DisplayDate) != 0)
  512. {
  513. DisplayDate = _calendar.DisplayDate;
  514. }
  515. }
  516. }
  517. private void OnDisplayDateChanged(AvaloniaPropertyChangedEventArgs e)
  518. {
  519. if (_calendar != null)
  520. {
  521. var value = (DateTime)e.NewValue;
  522. SetCalendarDisplayDate(value);
  523. }
  524. }
  525. private void SetCalendarDisplayDateStart(DateTime? value)
  526. {
  527. _calendar.DisplayDateStart = value;
  528. if (_calendar.DisplayDateStart.HasValue && DisplayDateStart.HasValue && DateTime.Compare(_calendar.DisplayDateStart.Value, DisplayDateStart.Value) != 0)
  529. {
  530. DisplayDateStart = _calendar.DisplayDateStart;
  531. }
  532. }
  533. private void OnDisplayDateStartChanged(AvaloniaPropertyChangedEventArgs e)
  534. {
  535. if (_calendar != null)
  536. {
  537. var value = (DateTime?)e.NewValue;
  538. SetCalendarDisplayDateStart(value);
  539. }
  540. }
  541. private void SetCalendarDisplayDateEnd(DateTime? value)
  542. {
  543. _calendar.DisplayDateEnd = value;
  544. if (_calendar.DisplayDateEnd.HasValue && DisplayDateEnd.HasValue && DateTime.Compare(_calendar.DisplayDateEnd.Value, DisplayDateEnd.Value) != 0)
  545. {
  546. DisplayDateEnd = _calendar.DisplayDateEnd;
  547. }
  548. }
  549. private void OnDisplayDateEndChanged(AvaloniaPropertyChangedEventArgs e)
  550. {
  551. if (_calendar != null)
  552. {
  553. var value = (DateTime?)e.NewValue;
  554. SetCalendarDisplayDateEnd(value);
  555. }
  556. }
  557. private void OnIsDropDownOpenChanged(AvaloniaPropertyChangedEventArgs e)
  558. {
  559. var oldValue = (bool)e.OldValue;
  560. var value = (bool)e.NewValue;
  561. if (_popUp != null && _popUp.Child != null)
  562. {
  563. if (value != oldValue)
  564. {
  565. if (_calendar.DisplayMode != CalendarMode.Month)
  566. {
  567. _calendar.DisplayMode = CalendarMode.Month;
  568. }
  569. if (value)
  570. {
  571. OpenDropDown();
  572. }
  573. else
  574. {
  575. _popUp.IsOpen = false;
  576. OnCalendarClosed(new RoutedEventArgs());
  577. }
  578. }
  579. }
  580. }
  581. private void OnSelectedDateChanged(AvaloniaPropertyChangedEventArgs e)
  582. {
  583. var addedDate = (DateTime?)e.NewValue;
  584. var removedDate = (DateTime?)e.OldValue;
  585. if (_calendar != null && addedDate != _calendar.SelectedDate)
  586. {
  587. _calendar.SelectedDate = addedDate;
  588. }
  589. if (SelectedDate != null)
  590. {
  591. DateTime day = SelectedDate.Value;
  592. // When the SelectedDateProperty change is done from
  593. // OnTextPropertyChanged method, two-way binding breaks if
  594. // BeginInvoke is not used:
  595. Threading.Dispatcher.UIThread.InvokeAsync(() =>
  596. {
  597. _settingSelectedDate = true;
  598. Text = DateTimeToString(day);
  599. _settingSelectedDate = false;
  600. OnDateSelected(addedDate, removedDate);
  601. });
  602. // When DatePickerDisplayDateFlag is TRUE, the SelectedDate
  603. // change is coming from the Calendar UI itself, so, we
  604. // shouldn't change the DisplayDate since it will automatically
  605. // be changed by the Calendar
  606. if ((day.Month != DisplayDate.Month || day.Year != DisplayDate.Year) && (_calendar == null || !_calendar.DatePickerDisplayDateFlag))
  607. {
  608. DisplayDate = day;
  609. }
  610. if(_calendar != null)
  611. _calendar.DatePickerDisplayDateFlag = false;
  612. }
  613. else
  614. {
  615. _settingSelectedDate = true;
  616. SetWaterMarkText();
  617. _settingSelectedDate = false;
  618. OnDateSelected(addedDate, removedDate);
  619. }
  620. }
  621. private void OnDateFormatChanged()
  622. {
  623. if (_textBox != null)
  624. {
  625. if (SelectedDate.HasValue)
  626. {
  627. Text = DateTimeToString(SelectedDate.Value);
  628. }
  629. else if (string.IsNullOrEmpty(_textBox.Text))
  630. {
  631. SetWaterMarkText();
  632. }
  633. else
  634. {
  635. DateTime? date = ParseText(_textBox.Text);
  636. if (date != null)
  637. {
  638. string s = DateTimeToString((DateTime)date);
  639. Text = s;
  640. }
  641. }
  642. }
  643. }
  644. private void OnSelectedDateFormatChanged(AvaloniaPropertyChangedEventArgs e)
  645. {
  646. OnDateFormatChanged();
  647. }
  648. private void OnCustomDateFormatStringChanged(AvaloniaPropertyChangedEventArgs e)
  649. {
  650. if(SelectedDateFormat == DatePickerFormat.Custom)
  651. {
  652. OnDateFormatChanged();
  653. }
  654. }
  655. private void OnTextChanged(AvaloniaPropertyChangedEventArgs e)
  656. {
  657. var oldValue = (string)e.OldValue;
  658. var value = (string)e.NewValue;
  659. if (!_suspendTextChangeHandler)
  660. {
  661. if (value != null)
  662. {
  663. if (_textBox != null)
  664. {
  665. _textBox.Text = value;
  666. }
  667. else
  668. {
  669. _defaultText = value;
  670. }
  671. if (!_settingSelectedDate)
  672. {
  673. SetSelectedDate();
  674. }
  675. }
  676. else
  677. {
  678. if (!_settingSelectedDate)
  679. {
  680. _settingSelectedDate = true;
  681. SelectedDate = null;
  682. _settingSelectedDate = false;
  683. }
  684. }
  685. }
  686. else
  687. {
  688. SetWaterMarkText();
  689. }
  690. }
  691. /// <summary>
  692. /// Raises the
  693. /// <see cref="E:Avalonia.Controls.DatePicker.DateValidationError" />
  694. /// event.
  695. /// </summary>
  696. /// <param name="e">
  697. /// A
  698. /// <see cref="T:Avalonia.Controls.DatePickerDateValidationErrorEventArgs" />
  699. /// that contains the event data.
  700. /// </param>
  701. protected virtual void OnDateValidationError(DatePickerDateValidationErrorEventArgs e)
  702. {
  703. DateValidationError?.Invoke(this, e);
  704. }
  705. private void OnDateSelected(DateTime? addedDate, DateTime? removedDate)
  706. {
  707. EventHandler<SelectionChangedEventArgs> handler = this.SelectedDateChanged;
  708. if (null != handler)
  709. {
  710. Collection<DateTime> addedItems = new Collection<DateTime>();
  711. Collection<DateTime> removedItems = new Collection<DateTime>();
  712. if (addedDate.HasValue)
  713. {
  714. addedItems.Add(addedDate.Value);
  715. }
  716. if (removedDate.HasValue)
  717. {
  718. removedItems.Add(removedDate.Value);
  719. }
  720. handler(this, new SelectionChangedEventArgs(SelectingItemsControl.SelectionChangedEvent, addedItems, removedItems));
  721. }
  722. }
  723. private void OnCalendarClosed(EventArgs e)
  724. {
  725. CalendarClosed?.Invoke(this, e);
  726. }
  727. private void OnCalendarOpened(EventArgs e)
  728. {
  729. CalendarOpened?.Invoke(this, e);
  730. }
  731. private void Calendar_DayButtonMouseUp(object sender, PointerReleasedEventArgs e)
  732. {
  733. Focus();
  734. IsDropDownOpen = false;
  735. }
  736. private void Calendar_DisplayDateChanged(object sender, CalendarDateChangedEventArgs e)
  737. {
  738. if (e.AddedDate != this.DisplayDate)
  739. {
  740. SetValue(DisplayDateProperty, (DateTime) e.AddedDate);
  741. }
  742. }
  743. private void Calendar_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
  744. {
  745. Debug.Assert(e.AddedItems.Count < 2, "There should be less than 2 AddedItems!");
  746. if (e.AddedItems.Count > 0 && SelectedDate.HasValue && DateTime.Compare((DateTime)e.AddedItems[0], SelectedDate.Value) != 0)
  747. {
  748. SelectedDate = (DateTime?)e.AddedItems[0];
  749. }
  750. else
  751. {
  752. if (e.AddedItems.Count == 0)
  753. {
  754. SelectedDate = null;
  755. return;
  756. }
  757. if (!SelectedDate.HasValue)
  758. {
  759. if (e.AddedItems.Count > 0)
  760. {
  761. SelectedDate = (DateTime?)e.AddedItems[0];
  762. }
  763. }
  764. }
  765. }
  766. private void Calendar_PointerPressed(object sender, PointerPressedEventArgs e)
  767. {
  768. if (e.MouseButton == MouseButton.Left)
  769. {
  770. e.Handled = true;
  771. }
  772. }
  773. private void Calendar_KeyDown(object sender, KeyEventArgs e)
  774. {
  775. Calendar c = sender as Calendar;
  776. Contract.Requires<ArgumentNullException>(c != null);
  777. if (!e.Handled && (e.Key == Key.Enter || e.Key == Key.Space || e.Key == Key.Escape) && c.DisplayMode == CalendarMode.Month)
  778. {
  779. Focus();
  780. IsDropDownOpen = false;
  781. if (e.Key == Key.Escape)
  782. {
  783. SelectedDate = _onOpenSelectedDate;
  784. }
  785. }
  786. }
  787. private void TextBox_GotFocus(object sender, RoutedEventArgs e)
  788. {
  789. IsDropDownOpen = false;
  790. }
  791. private void TextBox_KeyDown(object sender, KeyEventArgs e)
  792. {
  793. if (!e.Handled)
  794. {
  795. e.Handled = ProcessDatePickerKey(e);
  796. }
  797. }
  798. private void TextBox_TextChanged()
  799. {
  800. if (_textBox != null)
  801. {
  802. _suspendTextChangeHandler = true;
  803. Text = _textBox.Text;
  804. _suspendTextChangeHandler = false;
  805. }
  806. }
  807. private void DropDownButton_PointerPressed(object sender, PointerPressedEventArgs e)
  808. {
  809. _ignoreButtonClick = _isPopupClosing;
  810. }
  811. private void DropDownButton_Click(object sender, RoutedEventArgs e)
  812. {
  813. if (!_ignoreButtonClick)
  814. {
  815. HandlePopUp();
  816. }
  817. else
  818. {
  819. _ignoreButtonClick = false;
  820. }
  821. }
  822. private void PopUp_Closed(object sender, EventArgs e)
  823. {
  824. IsDropDownOpen = false;
  825. if(!_isPopupClosing)
  826. {
  827. _isPopupClosing = true;
  828. Threading.Dispatcher.UIThread.InvokeAsync(() => _isPopupClosing = false);
  829. }
  830. }
  831. private void HandlePopUp()
  832. {
  833. if (IsDropDownOpen)
  834. {
  835. Focus();
  836. IsDropDownOpen = false;
  837. }
  838. else
  839. {
  840. ProcessTextBox();
  841. }
  842. }
  843. private void OpenDropDown()
  844. {
  845. if (_calendar != null)
  846. {
  847. _calendar.Focus();
  848. OpenPopUp();
  849. _calendar.ResetStates();
  850. OnCalendarOpened(new RoutedEventArgs());
  851. }
  852. }
  853. private void OpenPopUp()
  854. {
  855. _onOpenSelectedDate = SelectedDate;
  856. _popUp.IsOpen = true;
  857. }
  858. /// <summary>
  859. /// Input text is parsed in the correct format and changed into a
  860. /// DateTime object. If the text can not be parsed TextParseError Event
  861. /// is thrown.
  862. /// </summary>
  863. /// <param name="text">Inherited code: Requires comment.</param>
  864. /// <returns>
  865. /// IT SHOULD RETURN NULL IF THE STRING IS NOT VALID, RETURN THE
  866. /// DATETIME VALUE IF IT IS VALID.
  867. /// </returns>
  868. private DateTime? ParseText(string text)
  869. {
  870. DateTime newSelectedDate;
  871. // TryParse is not used in order to be able to pass the exception to
  872. // the TextParseError event
  873. try
  874. {
  875. newSelectedDate = DateTime.Parse(text, DateTimeHelper.GetCurrentDateFormat());
  876. if (Calendar.IsValidDateSelection(this._calendar, newSelectedDate))
  877. {
  878. return newSelectedDate;
  879. }
  880. else
  881. {
  882. var dateValidationError = new DatePickerDateValidationErrorEventArgs(new ArgumentOutOfRangeException(nameof(text), "SelectedDate value is not valid."), text);
  883. OnDateValidationError(dateValidationError);
  884. if (dateValidationError.ThrowException)
  885. {
  886. throw dateValidationError.Exception;
  887. }
  888. }
  889. }
  890. catch (FormatException ex)
  891. {
  892. DatePickerDateValidationErrorEventArgs textParseError = new DatePickerDateValidationErrorEventArgs(ex, text);
  893. OnDateValidationError(textParseError);
  894. if (textParseError.ThrowException)
  895. {
  896. throw textParseError.Exception;
  897. }
  898. }
  899. return null;
  900. }
  901. private string DateTimeToString(DateTime d)
  902. {
  903. DateTimeFormatInfo dtfi = DateTimeHelper.GetCurrentDateFormat();
  904. switch (SelectedDateFormat)
  905. {
  906. case DatePickerFormat.Short:
  907. return string.Format(CultureInfo.CurrentCulture, d.ToString(dtfi.ShortDatePattern, dtfi));
  908. case DatePickerFormat.Long:
  909. return string.Format(CultureInfo.CurrentCulture, d.ToString(dtfi.LongDatePattern, dtfi));
  910. case DatePickerFormat.Custom:
  911. return string.Format(CultureInfo.CurrentCulture, d.ToString(CustomDateFormatString, dtfi));
  912. }
  913. return null;
  914. }
  915. private bool ProcessDatePickerKey(KeyEventArgs e)
  916. {
  917. switch (e.Key)
  918. {
  919. case Key.Enter:
  920. {
  921. SetSelectedDate();
  922. return true;
  923. }
  924. case Key.Down:
  925. {
  926. if ((e.Modifiers & InputModifiers.Control) == InputModifiers.Control)
  927. {
  928. HandlePopUp();
  929. return true;
  930. }
  931. break;
  932. }
  933. }
  934. return false;
  935. }
  936. private void ProcessTextBox()
  937. {
  938. SetSelectedDate();
  939. IsDropDownOpen = true;
  940. _calendar.Focus();
  941. }
  942. private void SetSelectedDate()
  943. {
  944. if (_textBox != null)
  945. {
  946. if (!string.IsNullOrEmpty(_textBox.Text))
  947. {
  948. string s = _textBox.Text;
  949. if (SelectedDate != null)
  950. {
  951. // If the string value of the SelectedDate and the
  952. // TextBox string value are equal, we do not parse the
  953. // string again if we do an extra parse, we lose data in
  954. // M/d/yy format.
  955. // ex: SelectedDate = DateTime(1008,12,19) but when
  956. // "12/19/08" is parsed it is interpreted as
  957. // DateTime(2008,12,19)
  958. string selectedDate = DateTimeToString(SelectedDate.Value);
  959. if (selectedDate == s)
  960. {
  961. return;
  962. }
  963. }
  964. DateTime? d = SetTextBoxValue(s);
  965. if (!SelectedDate.Equals(d))
  966. {
  967. SelectedDate = d;
  968. }
  969. }
  970. else
  971. {
  972. if (SelectedDate != null)
  973. {
  974. SelectedDate = null;
  975. }
  976. }
  977. }
  978. else
  979. {
  980. DateTime? d = SetTextBoxValue(_defaultText);
  981. if (!SelectedDate.Equals(d))
  982. {
  983. SelectedDate = d;
  984. }
  985. }
  986. }
  987. private DateTime? SetTextBoxValue(string s)
  988. {
  989. if (string.IsNullOrEmpty(s))
  990. {
  991. SetValue(TextProperty, s);
  992. return SelectedDate;
  993. }
  994. else
  995. {
  996. DateTime? d = ParseText(s);
  997. if (d != null)
  998. {
  999. SetValue(TextProperty, s);
  1000. return d;
  1001. }
  1002. else
  1003. {
  1004. // If parse error: TextBox should have the latest valid
  1005. // SelectedDate value:
  1006. if (SelectedDate != null)
  1007. {
  1008. string newtext = this.DateTimeToString(SelectedDate.Value);
  1009. SetValue(TextProperty, newtext);
  1010. return SelectedDate;
  1011. }
  1012. else
  1013. {
  1014. SetWaterMarkText();
  1015. return null;
  1016. }
  1017. }
  1018. }
  1019. }
  1020. private void SetWaterMarkText()
  1021. {
  1022. if (_textBox != null)
  1023. {
  1024. if (string.IsNullOrEmpty(Watermark) && !UseFloatingWatermark)
  1025. {
  1026. DateTimeFormatInfo dtfi = DateTimeHelper.GetCurrentDateFormat();
  1027. Text = string.Empty;
  1028. _defaultText = string.Empty;
  1029. var watermarkFormat = "<{0}>";
  1030. string watermarkText;
  1031. switch (SelectedDateFormat)
  1032. {
  1033. case DatePickerFormat.Long:
  1034. {
  1035. watermarkText = string.Format(CultureInfo.CurrentCulture, watermarkFormat, dtfi.LongDatePattern.ToString());
  1036. break;
  1037. }
  1038. case DatePickerFormat.Short:
  1039. default:
  1040. {
  1041. watermarkText = string.Format(CultureInfo.CurrentCulture, watermarkFormat, dtfi.ShortDatePattern.ToString());
  1042. break;
  1043. }
  1044. }
  1045. _textBox.Watermark = watermarkText;
  1046. }
  1047. else
  1048. {
  1049. _textBox.ClearValue(TextBox.WatermarkProperty);
  1050. }
  1051. }
  1052. }
  1053. private static bool IsValidSelectedDateFormat(DatePickerFormat value)
  1054. {
  1055. return value == DatePickerFormat.Long
  1056. || value == DatePickerFormat.Short
  1057. || value == DatePickerFormat.Custom;
  1058. }
  1059. private static DatePickerFormat ValidateSelectedDateFormat(DatePicker dp, DatePickerFormat format)
  1060. {
  1061. if(IsValidSelectedDateFormat(format))
  1062. {
  1063. return format;
  1064. }
  1065. else
  1066. {
  1067. throw new ArgumentOutOfRangeException(nameof(format), "DatePickerFormat value is not valid.");
  1068. }
  1069. }
  1070. private static string ValidateDateFormatString(DatePicker dp, string formatString)
  1071. {
  1072. if(string.IsNullOrWhiteSpace(formatString))
  1073. {
  1074. throw new ArgumentException("DateFormatString value is not valid.", nameof(formatString));
  1075. }
  1076. else
  1077. {
  1078. return formatString;
  1079. }
  1080. }
  1081. private static DateTime DiscardDayTime(DateTime d)
  1082. {
  1083. int year = d.Year;
  1084. int month = d.Month;
  1085. DateTime newD = new DateTime(year, month, 1, 0, 0, 0);
  1086. return newD;
  1087. }
  1088. private static DateTime? DiscardTime(DateTime? d)
  1089. {
  1090. if (d == null)
  1091. {
  1092. return null;
  1093. }
  1094. else
  1095. {
  1096. DateTime discarded = (DateTime) d;
  1097. int year = discarded.Year;
  1098. int month = discarded.Month;
  1099. int day = discarded.Day;
  1100. DateTime newD = new DateTime(year, month, day, 0, 0, 0);
  1101. return newD;
  1102. }
  1103. }
  1104. }
  1105. }