Search code examples
c#wpfdatepicker

C# WPF Update the blackoutDates in DatePickers


I'm writing a C# WPF application for a kiosk (so a long-time running app).

In the main window there are two DatePickers that must select only today and future days.
So I checked the BlackoutDate property and the X signs appear in the dates of the past.
This is correct for NOW (or better, when I run the application).

The time passes .. the new day arrives but the list of the BlackoutDays is not updated then it is possible to select the day(s) before (new) now.
It seems that the BlackoutDays is updated/stopped to the launch date of the application.

How can I update the control to avoid the selection of past days without re-run the application?


Solution

  • This is my solution:
    i setup a 30 minutes timer to detect the after-midnight moments. In that moment the code updates the control in the GUI context.

    private bool _updateDp = false;
    
    private void timerUpdateDatePicker_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            int hour = DateTime.Now.Hour;
            LogManager.Write($"[Main][timerUpdDp] hour: {hour} - update: {_updateDp}");
            if (hour == 0)
            {
                if (_updateDp) // only once
                {
                    LogManager.Write("[Main][timerUpdDp] update1");
                    dtDataPartenza.Dispatcher.Invoke( delegate
                    {
                        LogManager.Write("[Main][timerUpdDp] update delegate");
                        dtDataPartenza.SelectedDate = DateTime.Now;
                        dtDataPartenza.BlackoutDates.AddDatesInPast();
                        dtDataRitorno.SelectedDate = DateTime.Now;
                        dtDataRitorno.BlackoutDates.AddDatesInPast();
                    });
                    _updateDp = false;
                }
            }
            else
            {
                _updateDp = true;
            }
        }