[Xamarin.Forms] How to Set DatePicker’s MaximumDate to Current Date in XAML

This short tutorial demonstrates how to set the MaximumDate property of the Xamarin.Forms DatePicker control to current date directly in XAML.

The code below shows that it can be achieved in two steps.

<?xml version="1.0" encoding="UTF-8" ?>
<ContentView
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    x:Class="XamarinFormsCookbook.Views.DatePickerMaximumDateCurrentDate.DatePickerMaximumDateCurrentDateControl">

    <ContentView.Content>

        <Frame BackgroundColor="CornflowerBlue" HasShadow="False" VerticalOptions="Start">
            <StackLayout Orientation="Horizontal" VerticalOptions="Start">
                <Label Text="Select date" TextColor="White" VerticalTextAlignment="Center"/>

                <DatePicker MaximumDate="{x:Static sys:DateTime.UtcNow}"
                            Format="dd.MM.yyyy"
                            VerticalOptions="Start"
                            />
            </StackLayout>
        </Frame>

    </ContentView.Content>
</ContentView>

First, you have to reference the System namespace within a ContentPage or a ContentView that contains the DatePicker (line 5).

Now, you can assign the value of the DateTime structure’s UtcNow or Now static field to the MaximumDate property of the DatePicker control (line 14).

That is all! You can find the code to this tutorial on GitHub: https://github.com/asigitov/XamarinFormsCookbook

Useful links

DateTime Struct – https://docs.microsoft.com/en-US/dotnet/api/system.datetime?view=net-5.0

Xamarin.Forms DatePicker – https://docs.microsoft.com/en-US/xamarin/xamarin-forms/user-interface/datepicker

%d