Home
WPF
DatePicker Example: SelectedDate
Updated Sep 28, 2022
Dot Net Perls
DatePicker. Often in user interfaces a date selection is needed to provide a scheduling function. In WPF, we can use the DatePicker to present a calendar pop-up window.
Getting started. Please create a new WPF project and drag a DatePicker control to the window. Next, we add a useful event handler to our control: SelectedDateChanged.
Example. Type "SelectedDateChanged" and Visual Studio will insert the C# event handler. Here we access the sender object (the DatePicker) and its SelectedDate property.
Info SelectedDate returns a nullable DateTime instance. When null, no date is selected.
And If the nullable DateTime is not null, we use it in the same way as any other DateTime struct.
Tip We invoke ToShortDateString on the returned DateTime—it contains no time information, only a date.
<Window x:Class="WpfApplication12.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> <DatePicker HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" SelectedDateChanged="DatePicker_SelectedDateChanged"/> </Grid> </Window>
using System; using System.Windows; using System.Windows.Controls; namespace WpfApplication12 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void DatePicker_SelectedDateChanged(object sender, SelectionChangedEventArgs e) { // ... Get DatePicker reference. var picker = sender as DatePicker; // ... Get nullable DateTime from SelectedDate. DateTime? date = picker.SelectedDate; if (date == null) { // ... A null object. this.Title = "No date"; } else { // ... No need to display the time. this.Title = date.Value.ToShortDateString(); } } } }
Calendar. There exists a Calendar control, which is the same as DatePicker but involves no pop-up window. A DatePicker can save space and improve the interface.
Calendar
Summary. There are many ways to accept input dates—a program could even parse a TextBox. But in cases where a date selection is needed, a DatePicker is worth consideration.
TextBox
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 28, 2022 (edit).
Home
Changes
© 2007-2025 Sam Allen