DateTimePicker.xaml.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.ComponentModel;
  3. using System.Globalization;
  4. using System.Windows;
  5. using System.Windows.Controls;
  6. namespace CustomControls
  7. {
  8. [DesignTimeVisible(false)]
  9. public partial class DateTimePicker : DatePicker, INotifyPropertyChanged
  10. {
  11. public string CustomFormat
  12. {
  13. get { return (string)GetValue(CustomFormatProperty); }
  14. set { SetValue(CustomFormatProperty, value); }
  15. }
  16. public readonly static DependencyProperty CustomFormatProperty = DependencyProperty.Register(
  17. "CustomFormat", typeof(string), typeof(DateTimePicker), new UIPropertyMetadata(""));
  18. public event PropertyChangedEventHandler PropertyChanged;
  19. private DateTime? _value;
  20. internal DateTime? Value
  21. {
  22. get => SelectedDate;
  23. set
  24. {
  25. _value = value;
  26. SelectedDate = value;
  27. }
  28. }
  29. public string FormattedValue
  30. {
  31. get
  32. {
  33. if (SelectedDate == null)
  34. return null;
  35. DateTime dateTime = SelectedDate.Value;
  36. if (_value != null)
  37. {
  38. DateTime timePart = _value.Value;
  39. dateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, timePart.Hour, timePart.Minute, timePart.Second, timePart.Millisecond);
  40. }
  41. return dateTime.ToString(CustomFormat);
  42. }
  43. set => Value = DateTime.ParseExact(value, CustomFormat, CultureInfo.CurrentCulture);
  44. }
  45. protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
  46. {
  47. base.OnPropertyChanged(e);
  48. if (e.Property.Name == "SelectedDate" || e.Property.Name == "CustomFormat")
  49. {
  50. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("FormattedValue"));
  51. }
  52. }
  53. public DateTimePicker()
  54. {
  55. InitializeComponent();
  56. Padding = new Thickness(2, 2, 0, 3);
  57. }
  58. }
  59. }