我想修改标准WPF DatePicker以允许一周选择。如果我返回单个DateTime作为SelectedDate,这很好,但我需要UI在鼠标悬停时选择整个星期行。
我继承并附加到selecteddatechange,以便它将返回StartDayOfWeek作为SelectedDate(下面的代码)。
我有一个关于如何突出显示整个星期的想法(使用鼠标事件)。我希望有一个更简单的方法。
// force selection to be for first previous start DOW
this.SelectedDateChanged += (sender, args) => {
var newDate = (DateTime) args.AddedItems[0];
while (newDate.DayOfWeek != FirstDayOfWeek)
newDate = newDate.AddDays(-1);
SelectedDate = newDate;
};
编辑
我添加了我当前的解决方案作为答案。还在寻找一个好方法来突出显示范围,而不是我目前的做法。
我想我会添加我目前的解决方案,这是黑色的任何日期不是第一天的星期,并确保如果他们超出我的10年范围,正确的日期被选择。
public class LocalizedWeekPicker : LocalizedDatePicker
{
/// <summary>
/// An LocalizedDatePicker that disallows selecting any date that does not have the same DOW as the FirstDayOfWeek property.
/// It does this by disabling the dates N (currently=10) years forward and backward from today as well as automatically updating the date
/// if you choose something more than 10 years away from today.
/// </summary>
public LocalizedWeekPicker() : base()
{
this.Loaded += (s1, a1) => {
this.IsTodayHighlighted = false;
if (SelectedDate.HasValue)
{
var tempDate = new DateTime(SelectedDate.Value.Ticks);
SelectedDate = DateTimeUtils.GetPreviousDateOnDayOfWeek(FirstDayOfWeek, tempDate);
}
DisableDays();
this.SelectedDateChanged += (s2, a2) => {
var tempDate = new DateTime(((DateTime)a2.AddedItems[0]).Ticks);
SelectedDate = DateTimeUtils.GetPreviousDateOnDayOfWeek(FirstDayOfWeek, tempDate);
};
};
}
// goes forward and back n years and disables dates that don't have the same start DOW as the FirstDayOfWeek
private void DisableDays()
{
int years = 10;
var current = DateTimeUtils.GetPreviousDateOnDayOfWeek(FirstDayOfWeek, DateTime.Now);
for (int weeks = 0; weeks < (52 * years); weeks++)
{
this.BlackoutDates.Add(new CalendarDateRange {Start = current.AddDays(1), End = current.AddDays(6)});
current = current.AddDays(7);
}
current = DateTimeUtils.GetPreviousDateOnDayOfWeek(FirstDayOfWeek, DateTime.Now);
for (int weeks = 0; weeks < (52 * years); weeks++)
{
this.BlackoutDates.Add(new CalendarDateRange { Start = current.AddDays(1), End = current.AddDays(6) });
current = current.AddDays(-7);
}
}
}