I need to allow user to select only the Sunday from my date picker so I need to disable other columns. But I couldn't find any solution for this. Currently I just check in the selection-changed event and clear the date if not valid. How do I disable the non-Sundays entirely?
2 Answers
The relevant section in @kalyan's suggested link regards blackout dates, and the DatePicker's BlackoutDates
property, which lets you specify ranges of dates that users cannot select.
That property is of type CalendarBlackoutDatesCollection
, which is a subclass of ObservableCollection<CalendarDateRange>
. Knowing this, you can programmatically add ranges that include the Monday through Saturday to this collection for all weeks to be displayed on your calendar.
An important consideration to note is described on the MSDN page for the BlackoutDates
property:
Adding a date to this collection when it is already selected or adding a date outside the range specified by DisplayDateStart and DisplayDateEnd will cause an ArgumentOutOfRangeException.
So make sure you know how those 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, a DateTimePicker's DisplayDateStart/End properties are set to null. The code above therefore blacks out ALL days except Sundays from January 1, 0001 AD through December 31, 9999. This results in extremely poor performance when the Calendar control is displayed and interacted with. So if you're going to use this technique, I strongly suggest constraining the picker's start and end dates (and therefore the number of blackout-date ranges) to sensible limits.

- 16,319
- 7
- 50
- 82
-
Thanks djacobson your answer works fine. It's bit slow with DateTime.MinValue and DateTime.MaxValue so I have changed them then it's work fine. Thanks again. – janitheshan Sep 29 '11 at 18:05
-
@janitheshan You're welcome - don't forget to mark the answer as Accepted when you have a chance, if it suits you. Thanks. :) – Dan J Sep 29 '11 at 20:35
Did you referred to the Calendar & DatePicker Walkthrough

- 11,704
- 8
- 43
- 67
-
yes kalyan but I couldn't find anything related to my issue. any way thanks for the reply. – janitheshan Sep 28 '11 at 14:13