#366 – Binding a Calendar Control’s SelectedDate Property to a Nullable DateTime

The SelectedDate property of a Calendar control reflects the currently selected date, if the SelectionMode is SingleDate, or the first date selected if the mode is SingleRange or MultipleRange.

You can use data binding to bind the SelectedDate property to a variable of type DateTime? (nullable DateTime).

In the example below, we bind SelectedDate to the FavoriteDay property of our data context.

    <StackPanel>
        <Calendar SelectionMode="SingleDate" SelectedDate="{Binding FavoriteDay}"/>
        <Button Content="Test" Click="Button_Click" Width="80" Margin="20"/>
    </StackPanel>

In the code-behind, we define the FavoriteDay property and set the data context to the parent class that contains the property.

        public DateTime? FavoriteDay { get; set; }

        public MainWindow()
        {
            this.InitializeComponent();
            this.DataContext = this;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string msg;

            if (FavoriteDay == null)
                msg = "I don't have a favorite day";
            else
                msg = string.Format("My favorite day is {0:D}", FavoriteDay);

            MessageBox.Show(msg);
        }

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