Condividi tramite


Quickstart: Adding a DatePicker (XAML)

[ This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation ]

Learn how to use a DatePicker to let users pick a localized date using touch, mouse, or keyboard input.

Prerequisites

  • Windows 8.1 or Windows Phone 8.1
  • Microsoft Visual Studio 2013
  • We assume that you can add controls to a basic Windows Runtime app using C++, C#, or Visual Basic. For instructions on adding a control, see Quickstart: Adding controls and handling events.

When to use a date picker

The date picker gives you a standardized way to let users pick a localized date using touch, mouse, or keyboard input. You can use the DatePicker control in its default form with a minimal amount of Extensible Application Markup Language (XAML) or other code, or you can customize it in a variety of ways.

The DatePicker supports each of the calendar systems supported by Windows. These calendars are specified in the Windows.Globalization.CalendarIdentifiers class. The DatePicker uses the correct calendar for your app's default language, or you can set the CalendarIdentifier property to use a specific calendar system.

To let the user pick a time value, use a TimePicker control. See Quickstart: Adding a TimePicker.

For more info, see Guidelines for DatePickers.

Adding a DatePicker

To add a DatePicker in XAML

  1. Add a DatePicker control to a parent container.

  2. To assign a label to the date picker, set the Header property to a string value.

  3. To assign a name to the date picker, set the x:Name attribute to a string value.

    To refer to a control in code, it must have a name. Otherwise, a name is not required.

This example shows how to create a simple DatePicker with a header.

<DatePicker x:Name=arrivalDatePicker Header="Arrival Date"/>

This DatePicker looks like this when the day selector is opened.

Using the date value

You can read the Date property in your code, or bind it to a System.DateTimeOffset (C#/VB) or Windows::Foundation::DateTime (C++) data object.

You typically read the Date property value when the user clicks a submit button on a form, or takes some other action to indicate that data entry is complete. The DatePicker has a DateChanged event. However, because the user sets the date in 3 different selectors, this event might occur several times before the user is done setting the date. If you use the DatePickerValueChangedEventArgs to get the date value in a DateChanged event handler, you shouldn't assume that the date entry is final.

To use the date value

  1. Bind the Date property to a System.DateTimeOffset (C#/VB) or Windows::Foundation::DateTime (C++) data object.

    - or -

  2. Set the x:Name attribute on the DatePicker to access it by name from your code.

  3. Read the Date property.

This example shows how to read the Date property of a DatePicker named arrivalDatePicker. When the user clicks a submit button, the code in the button click handler verifies that the selected arrival date is in the future. The user is then notified whether the date is set or needs to be corrected.

<StackPanel Orientation="Horizontal" Height="60">
    <DatePicker x:Name="arrivalDatePicker" Header="Arrival Date"/>
    <Button Content="Submit" Click="SubmitButton_Click" 
            Margin="5,0,0,-2" VerticalAlignment="Bottom"/>
    <TextBlock x:Name="Control1Output"/>
</StackPanel>
private void SubmitButton_Click(object sender, RoutedEventArgs e)
{
    if (VerifyDateIsFuture(arrivalDatePicker.Date) == true)
    {
        Control1Output.Text = string.Format("Thank you. Your arrival is set for {0}.",
            arrivalDatePicker.Date.ToString("D"));

        // In a real app, you'd probably set a value on your data object, like this:
        //_reservation.ArrivalDate = arrivalDatePicker.Date;               
    }
    else
    {
        Control1Output.Text = "Arrival date must be later than today."; 
    }
}

private bool VerifyDateIsFuture(DateTimeOffset date)
{
    if (date > DateTimeOffset.Now)
    {
        return true;
    }
    return false;
}

Initializing the date value

By default, the DatePicker initializes to the current date. You can set the Date property to a different default date if you need to. You typically put this code wherever you have your other page initialization code, such as in the page's OnNavigatedTo method override, or in the date picker's Loaded event.

You can't set the date picker's default date in XAML.

Here, the OnNavigatedTo method override is used. The Date property is set to default to 2 months from the current date, and the minimum year is set to the current year.

<DatePicker x:Name=arrivalDatePicker Header="Arrival Date"/>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    // Set the default date to 2 months from the current date.
    arrivalDatePicker.Date = DateTimeOffset.Now.AddMonths(2);

    // Set the minimum year to the current year.
    arrivalDatePicker.MinYear = DateTimeOffset.Now;
}

In this example, the Loaded event is used, and the Date property is set to a specific date. In this case, the sender parameter is used to access the DatePicker, so any DatePicker could subscribe to this event.

<DatePicker x:Name=arrivalDatePicker Header="Arrival Date" Loaded="DatePicker_Loaded"/>
private void DatePicker_Loaded(object sender, RoutedEventArgs e)
{
    DatePicker picker = sender as DatePicker;
    DateTimeOffset newDate = DateTimeOffset.Now;
    DateTimeOffset.TryParse("4/17/2013", out newDate);

    if (picker != null)
    {
        picker.Date = newDate;
        picker.MinYear = DateTimeOffset.Now;
    }
}

Formatting the day, month, and year selectors

Note  This section applies to Windows Store apps using C++, C#, or Visual Basic. Formatting is ignored in Windows Phone Store apps.

You can change the format of the date picker's day, month, and year selectors, or hide a selector completely.

The string content of each selector (ComboBox) in the DatePicker is created by a DateTimeFormatter. You tell the DateTimeFormatter how to format the value by providing a string that is either a format template or a format pattern. Common templates and patterns to use with the DatePicker are listed in the following table.

format pattern format template
{day.integer} | {day.integer(n)} day
{dayofweek.full} | {dayofweek.abbreviated} | {dayofweek.abbreviated(n)} dayofweek | dayofweek.full | dayofweek.abbreviated
{month.integer} | {month.integer(n)} month.numeric
{month.full} | {month.abbreviated} | {month.abbreviated(n)} month | month.full | month.abbreviated
{year.full} | {year.abbreviated} | {year.abbreviated(n)} year | year.full | year.abbreviated
{era.full} | {era.abbreviated} | {era.abbreviated(n)} n/a

 

In some cases, using a format pattern gives you more precise control over the formatting than a format template. For example, you can use a format pattern to specify that the day picker always shows 2 digits, including a leading 0 when needed ({day.integer(2)}). You can also combine multiple format patterns. For example, you can combine the {day} and {dayofweek.abbreviated} formats to make the day picker show both the numeric date and the day of the week, like this: 14 Thu.

For the complete list of format templates and format patterns, see the Remarks section of the DateTimeFormatter class documentation.

To format the day, month, and year selectors

  1. Format the day selector by setting the DayFormat property. Hide the day selector by setting the DayVisible property to false.
  2. Format the month selector by setting the MonthFormat property. Hide the month selector by setting the MonthVisible property to false.
  3. Format the year selector by setting the YearFormat property. Hide the year selector by setting the YearVisible property to false.

Here's a DatePicker formatted using format templates, and a DatePicker formatted using format strings. Both DatePickers look the same when the app is run because the formatting is equivalent.

<!-- DatePicker formatted using format templates. -->
<DatePicker DayFormat="day" MonthFormat="month.numeric" YearFormat="year.abbreviated"/>

<!-- DatePicker formatted using format patterns. -->
<DatePicker DayFormat="{}{day.integer}" MonthFormat="{}{month.integer}" YearFormat="{}{year.abbreviated}"/>

Here's a DatePicker that combines 2 format patterns to display both the numeric date and the day of the week in the day selector. There is no equivalent format template for this format. The year field is hidden by setting the YearVisible property to false.

<DatePicker DayFormat="{}{day.integer} ({dayofweek.abbreviated})" YearVisible="False"/>

The formatted DatePicker looks like this.

Samples

To learn more about the DatePicker control, download the XAML DatePicker and TimePicker controls sample.

Summary and next steps

You learned how to use a DatePicker control to let users pick a localized date in your app.

Learn how to use a TimePicker control to let users pick a time value in the Quickstart: Adding a TimePicker tutorial.