C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
SelectedDateChanged: 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.
PropertyNullableAnd: If the nullable DateTime is not null, we use it in the same way as any other DateTime struct.
DateTimeTip: We invoke ToShortDateString on the returned DateTime—it contains no time information, only a date.
Example markup: XAML
<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>
Example code: C#
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();
}
}
}
}