WPF: binding viewmodel property of type DateTime to Calendar inside ItemsControl

后端 未结 4 588
说谎
说谎 2021-02-08 07:55

i have a problem with WPF Binding. I want to bind a list of Months to a ItemsControl that shows a Calendar Control for each month. But each rendered Calendar shows DateTime.Now,

相关标签:
4条回答
  • 2021-02-08 08:07

    Does this fit your needs?

    <Calendar SelectedDate="{Binding Path=CurrentDate}"
              DisplayDate="{Binding Path=SelectedDate,
                                    RelativeSource={RelativeSource Self}, 
                                    Mode=OneWay}" />
    
    0 讨论(0)
  • 2021-02-08 08:13

    The issue appears to be with how the Calendar initializes the DisplayDate property. It currently does it like this:

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

    It appears that even though the DisplayDate is being initialized before the binding is established, it will still be pushed back to the binding source as if it were set after. This is most likely a bug.

    You can work around it using something like:

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

    Or you could establish the binding at a later time (i.e. when the Calendar is loaded) using an event handler or attached behavior.

    0 讨论(0)
  • 2021-02-08 08:17

    I did read somewhere that if you bind a list box to a set of selected items (such as from another list box), it only shows the first selected item as selected on the second list box. I'm not sure if this is relevant here, but it looks like it could be.

    0 讨论(0)
  • 2021-02-08 08:20

    Try binding to SelectedDate instead of DisplayDate. Alternatively, see if it works better if you set IsTodayHighlighted="false".

    0 讨论(0)
提交回复
热议问题