WPF Datepicker making only a list of dates selecta

2019-06-25 08:10发布

I'm not sure if this is possible but is it possible to make only a list of dates selectable in a wpf datepicker?

I need to make sure that the use can only select from a certain amount of dates. I can do this with a dropdownlist, but with a datepicker it would be much nicer.

Any ideas?

3条回答
乱世女痞
2楼-- · 2019-06-25 08:23

The DatePicker has the following properties to control which dates should be selectable:

DisplayDateStart : The first date to include in the Calendar popup.
DisplayDateEnd : The last date to include in the Calendar popup.

So if you have a list containing allowed dates, you can set DisplayDateStart to the first item in the list, and DisplayDateEnd to the last item in the list.

That would prevent users from selecting dates outside that range.

To handle cases where the list of allowed dates contains gaps, you can use the BlackoutDates property to make ranges of dates not selectable.

So to add the dates that are not present in the list as blacked out, you can do something like the following.

Only the dates within the list are shown in the calendar popup, and the dates not in the list are blacked out so they can't be selected.

var dates = new List<DateTime>
{
    new DateTime(2013, 1, 5),
    new DateTime(2013, 1, 6),
    new DateTime(2013, 1, 7),
    new DateTime(2013, 1, 8),
    new DateTime(2013, 1, 15),
    new DateTime(2013, 1, 16),
    new DateTime(2013, 1, 28),
    new DateTime(2013, 1, 29),
    new DateTime(2013, 2, 9),
    new DateTime(2013, 2, 12),
    new DateTime(2013, 2, 13),
    new DateTime(2013, 2, 17),
    new DateTime(2013, 2, 18)
};

var firstDate = dates.First();
var lastDate = dates.Last();
var dateCounter = firstDate;

foreach (var d in dates.Skip(1))
{
    if (d.AddDays(-1).Date != dateCounter.Date)
    {
        dtp.BlackoutDates.Add(
            new CalendarDateRange(dateCounter.AddDays(1), d.AddDays(-1)));
    }

    dateCounter = d;
}

dtp.DisplayDateStart = firstDate;
dtp.DisplayDateEnd = lastDate;

If the allowed dates are very far apart, this would probably not be very user friendly, since it would be pretty annoying to have 90% of the dates blacked out. In that case a ComboBox might be better.

查看更多
Melony?
3楼-- · 2019-06-25 08:23

You need to create your own ControlTemplate. The easiest way is to take the default template (you can download it from below URL ) and change the parts you want.

http://archive.msdn.microsoft.com/wpfsamples#themes

查看更多
聊天终结者
4楼-- · 2019-06-25 08:26

You can do what you want using the BlackoutDates collection to prevent the user from selecting all the dates you want to avoid.

Code:

myDatePicker.BlackoutDates.Add(myCalendarDateRange);

XAML:

<DatePicker Name="myDatePicker">
    <DatePicker.BlackoutDates>
        <CalendarDateRange Start="02.20.2013" End="02.22.2013" />
    </DatePicker.BlackoutDates>
</DatePicker>
查看更多
登录 后发表回答