0

我想修改标准 WPF DatePicker 以允许选择一周。如果我返回单个 DateTime 作为 SelectedDate 很好,但是当鼠标悬停时我需要 UI 来选择整个星期行。

我继承并附加到 SelectedDateChanged 以便它将 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;
        };

编辑

我添加了我当前的解决方案作为答案。仍在寻找一种突出范围的好方法,而不是我目前的做法。

4

1 回答 1

0

想我会添加我当前的解决方案,即涂黑不属于 FirstDayOfWeek 的任何日期,并确保如果它们超出我的 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);
        }
    }
}
于 2013-03-11T15:02:26.800 回答