#367 – You Can’t Bind to a Calendar Control’s SelectedDates Property

A Calendar control’s SelectedDate property (single selected date) is read/write, so you are able to use data binding to bind it to a nullable DateTime.

The SelectedDates property (collection of selected dates), on the other hand, is read-only.  This means that you can’t bind to the SelectedDates property.

If you want to store a Calendar control’s set of currently selected dates in a variable, you can handle the calendar’s SelectedDatesChanged event.

XAML fragment:

        <Calendar SelectionMode="MultipleRange" SelectedDatesChanged="Calendar_SelectedDatesChanged"/>

Code-behind, where we store selected dates in array:

        public DateTime[] MyVacation { get; set; }

        private void Calendar_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
        {
            System.Windows.Controls.Calendar cal = (System.Windows.Controls.Calendar)sender;

            MyVacation = cal.SelectedDates.ToArray();
        }

This event handler will be called whenever the user selects or unselects dates in the Calendar control.  Because we reset the MyVacation array in the handler, it will always reflect the current set of selected dates.

Advertisements