Home
WPF
Calendar Example: SelectedDate
Updated Sep 27, 2022
Dot Net Perls
Calendar. This allows the user to select a day. As with the similar DatePicker control, we access the SelectedDate property. We use the SelectedDatesChanged event.
Get started. Drag a Calendar control the WPF window. Press tab and Visual Studio inserts the event handler (Calendar_SelectedDatesChanged). This runs when a date is selected.
Example code. In this C# method, we cast the "sender" object to a Calendar reference with an as-cast. The SelectedDate property returns a nullable 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.
<Window x:Class="WpfApplication21.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Calendar HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" SelectedDatesChanged="Calendar_SelectedDatesChanged"/> </Grid> </Window>
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() { InitializeComponent(); } 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. One important event is SelectedDatesChanged—with it, we can detect when the user selects a day within the control.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 27, 2022 (edit).
Home
Changes
© 2007-2025 Sam Allen