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

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Pingback: Dew Drop – August 17, 2011 | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: