How do create a DatePicker with only Sundays enabled?

青春壹個敷衍的年華 提交于 2019-12-10 13:45:44

问题


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?


回答1:


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.




回答2:


Did you referred to the Calendar & DatePicker Walkthrough



来源:https://stackoverflow.com/questions/7579777/how-do-create-a-datepicker-with-only-sundays-enabled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!