How do create a DatePicker with only Sundays enabled?
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 dat开发者_StackOverflow中文版e if not valid. How do I disable the non-Sundays entirely?
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.
Did you referred to the Calendar & DatePicker Walkthrough
精彩评论