Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

WPF Calendar Example: SelectedDate

This WPF article uses the Calendar control. It uses the SelectedDatesChanged event handler. It accesses the SelectedDate property.

Calendar allows the user to select a day. It is always visible.

No pop-up windows are shown. As with the similar DatePicker control, we access the SelectedDate property. We use the SelectedDatesChanged event.


Example. First, we drag a Calendar control the WPF window. To detect when a date is selected on the Calendar, we add a "SelectedDatesChanged" attribute. Press tab and Visual Studio inserts the event handler (Calendar_SelectedDatesChanged).

In this C# method, we cast the "sender" object to a Calendar reference with an as-cast. The SelectedDate property returns a nullable DateTime. This means it is a struct, but may be null.

AsNullable DateTime

And: We use the HasValue property on the nullable type to determine whether the inner DateTime exists or not.

Then: We get a reference to the DateTime indicated by the Calendar at this point. We call ToShortDateString on it.

Based on:

.NET 4.5

Example markup: XAML

<Window x:Class="WpfApplication21.MainWindow"
	Title="MainWindow" Height="350" Width="525">

Example code: C#

using System;
using System.Windows;
using System.Windows.Controls;

namespace WpfApplication21
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
	public MainWindow()

	private void Calendar_SelectedDatesChanged(object sender,
	    SelectionChangedEventArgs e)
	    // ... Get reference.
	    var calendar = sender as Calendar;

	    // ... See if a date is selected.
	    if (calendar.SelectedDate.HasValue)
		// ... Display SelectedDate in Title.
		DateTime date = calendar.SelectedDate.Value;
		this.Title = date.ToShortDateString();


Summary. The Calendar control displays a month-based calendar. It can be configured in many ways. One important, and useful, event is SelectedDatesChanged. With it, we can detect when the user selects a day within the control.