#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);
        }