How to create a datepicker with sundays enabled only?

I need to allow the user to select only Sunday from my date picker, so I need to disable other columns. But I could not find a solution for this. I am currently just checking the event with the changed selection and clear the date if it is not valid. How to completely disable the weekend?

+4
source share
2 answers

The corresponding section in @kalyan offered a link regarding shutdown dates, and DatePicker BlackoutDates , which allows you to specify date ranges that users cannot select.

This property is of type CalendarBlackoutDatesCollection , which is a subclass of ObservableCollection<CalendarDateRange> . Knowing this, you can programmatically add ranges that include Monday through Saturday to this collection for all the weeks that will be displayed on your calendar.

An important description note is described on the MSDN page for the BlackoutDates property:

Adding a date to this collection when it is already selected or a date is added outside the range specified by DisplayDateStart and DisplayDateEnd will throw an ArgumentOutOfRangeException.

So make sure you know how these two properties are defined.

A simple example:

 //Code assumes a DateTimePicker declared in XAML with its Name property set to "calendar" var minDate = calendar.DisplayDateStart ?? DateTime.MinValue; var maxDate = calendar.DisplayDateEnd ?? DateTime.MaxValue; //pardon the somewhat clunky DateTime.MaxValue handling here; it prevents an overflow //when actually adding dates near the maximum for (var d = minDate; d <= maxDate && (DateTime.MaxValue - d.AddDays(7)).Days > 7; d = d.AddDays(7)) { var range = new CalendarDateRange(d, d.AddDays(5)); calendar.BlackoutDates.Add(range); } 

Please note: by default, the DateTimePicker DisplayDateStart / End properties are null. Thus, the above code obscures ALL days except Sunday from January 1, 0001 to December 31, 9999. This results in extremely poor performance when displaying and interacting with a calendar control. Therefore, if you intend to use this technique, I highly recommend limiting the start and end dates of the selection (and therefore the number of disconnect date ranges) to reasonable limits.

+9
source

All Articles