Calendar.DisplayDate TwoWay Binding传播回默认值

时间:2011-02-23 10:09:22

标签: wpf xaml data-binding calendar

我有2个日历,我想在本月和下一个日历中显示,但两者都有相同的选定日期。我在模型中使用2个简单属性ShownDate来存储和计算当前和下个月。

<Calendar SelectedDate="{Binding Date, Mode=TwoWay}" 
          DisplayDate="{Binding ShownDate, Mode=TwoWay}"
          Margin="4" AllowDrop="True" />
<Calendar SelectedDate="{Binding Date, Mode=TwoWay}" 
          DisplayDate="{Binding ShownDate2, Mode=TwoWay}"
          Margin="4" AllowDrop="True" />

我意识到在显示它之前,我在ShownDate2属性设置当前月份(UpdateSource)中传播到我的模型,因此忘记了我的默认值(它必须是下个月,而不是当前)。它发生在我的值的任何查询之前(稍后会发生UpdateTarget)。

这是Calendar.DisplayDate绑定行为中的错误吗?

请注意,所有这些都包含在由ContentPresenter绘制的DataTemplate中,但我认为没关系。

更新: 现在我确定DataTemplates很重要,但无法在一个简单的项目中重现这个bug。我还是迷路了。

1 个答案:

答案 0 :(得分:1)

我认为这可能与WPF: binding viewmodel property of type DateTime to Calendar inside ItemsControl重复,但要总结一下:

问题似乎是Calendar如何初始化DisplayDate属性。它目前是这样的:

public Calendar() {
    // ...
    base.SetCurrentValueInternal(DisplayDateProperty, DateTime.Today);
}

即使在建立绑定之前初始化DisplayDate,它仍然会被推回到绑定源,就好像它被设置之后一样。这很可能是一个错误。

您可以使用以下内容解决此问题:

public class MyCalendar : Calendar {
    public MyCalendar() {
        this.ClearValue(DisplayDateProperty);
    }
}

或者您可以在以后建立绑定(即加载日历时)。

相关问题