DatePicker的DisplayDates未正确更新,并且不显示其新值

时间:2012-07-08 22:59:04

标签: c# wpf datepicker

如果我在dtpWeek1中选择了8/6/2012,我希望下面的代码可以将dtpWeek2移动到8/13,dtpWeek3移动到8/20等等。

但是,无论我在dtp1中选择什么,它都会将dtp2移动到本月的第一天之后的一周(IOW,它始终是第8个)。 DatePickers的其余部分(从dtp3到dtp9)工作正常,因为它们比前一个更长 - 但它们不应该基于我在dtp1中选择的内容,因为它们始终是第15,22和29日(大多数Februarys除外)。

就好像当我移动到另一个月时,DisplayDate变为/ 1 /(这并非完全不合逻辑/令人惊讶),但当我点击该月内的某个特定日期(例如第6个)时,它会忽略它

我使用了错误的活动吗?错误的方法论?

private void dtpWeek1_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
{
    dtpWeek2.DisplayDate = dtpWeek1.DisplayDate.AddDays(7);
    dtpWeek3.DisplayDate = dtpWeek1.DisplayDate.AddDays(14);
    dtpWeek4.DisplayDate = dtpWeek1.DisplayDate.AddDays(21);
    dtpWeek5.DisplayDate = dtpWeek1.DisplayDate.AddDays(28);
    dtpWeek6.DisplayDate = dtpWeek1.DisplayDate.AddDays(35);
    dtpWeek7.DisplayDate = dtpWeek1.DisplayDate.AddDays(42);
    dtpWeek8.DisplayDate = dtpWeek1.DisplayDate.AddDays(49);
    // TODO: Only add week 9 if it is within the month following the first month
    dtpWeek9.DisplayDate = dtpWeek1.DisplayDate.AddDays(56);
}

此外,以编程方式分配了DisplayDates的所有DatePicker组件继续显示“选择日期” - 基于属性名称(DisplayDate),我希望它们实际显示其DisplayDate。他们为什么不呢?我怎样才能让他们真正这样做?如果我点击它们将它们放下,我看到日期是如上所述(第8,15等),但为什么它们会以这种方式隐藏它们的“光”呢?

最后,在旁注中,以这种方式编写代码会产生什么后果(我认为这可能会更慢甚至不可靠):

private void dtpWeek1_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
{
    dtpWeek2.DisplayDate = dtpWeek1.DisplayDate.AddDays(7);
    dtpWeek3.DisplayDate = dtpWeek2.DisplayDate.AddDays(7);
    dtpWeek4.DisplayDate = dtpWeek3.DisplayDate.AddDays(7);
    dtpWeek5.DisplayDate = dtpWeek4.DisplayDate.AddDays(7);
    dtpWeek6.DisplayDate = dtpWeek5.DisplayDate.AddDays(7);
    dtpWeek7.DisplayDate = dtpWeek6.DisplayDate.AddDays(7);
    dtpWeek8.DisplayDate = dtpWeek7.DisplayDate.AddDays(7);
    dtpWeek9.DisplayDate = dtpWeek8.DisplayDate.AddDays(7);
}

将代码更改为:

    dtpWeek2.SelectedDate = dtpWeek1.DisplayDate.AddDays(7);
    dtpWeek3.SelectedDate = dtpWeek1.DisplayDate.AddDays(14);
    dtpWeek4.SelectedDate = dtpWeek1.DisplayDate.AddDays(21);
    dtpWeek5.SelectedDate = dtpWeek1.DisplayDate.AddDays(28);
    dtpWeek6.SelectedDate = dtpWeek1.DisplayDate.AddDays(35);
    dtpWeek7.SelectedDate = dtpWeek1.DisplayDate.AddDays(42);
    dtpWeek8.SelectedDate = dtpWeek1.DisplayDate.AddDays(49);
    dtpWeek9.SelectedDate = dtpWeek1.DisplayDate.AddDays(56);

解决了未显示日期的问题。然而,他们仍然表现得好像我选择了8/1而不是8/6。值为:

8/6
8/8
8/15
8/22
8/29
etc.

1 个答案:

答案 0 :(得分:1)

好的,将评论转换为答案:SelectedDate属性应该像这样使用:

dtpWeek2.SelectedDate = dtpWeek1.SelectedDate.Value.AddDays(7);

SelectedDateDateTime?(可空),因此右侧是.Value