#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

#365 – SelectedDate and SelectedDates Properties of Calendar Control

The SelectedDate property of a Calendar control is a nullable DateTime (System.DateTime?) that represents a single selected date.

The SelectedDates property is an instance of SelectedDatesCollection, which is an ObservableCollection that contains DateTime values.  It represents the set of currently selected dates.

If the SelectionMode is None, or if no date is currently selected:

  • SelectedDate is null
  • SelectedDates is an empty collection

If SelectionMode is SingleDate and a date is selected:

  • SelectedDate contains a single DateTime value
  • SelectedDates contains a single DateTime element in the collection

If SelectionMode is SingleRange or MultipleRange and at least one date is selected:

  • SelectedDate contains a single DateTime value, equivalent to the first element in the SelectedDates collection
  • SelectedDates contains a DateTime element for each date that is currently selected