Using DateOnly in the .NET MAUI DatePicker
If your application needs to store or manipulate only the dates without times, you can take advantage of the DateOnly
struct when working with the DatePicker control.
You can set a DateOnly
value to the MinimumDate
, MaximumDate
, Date
, and DefaultHighlightedDate
properties by using the Telerik DateOnlyToDateTimeConverter
converter. The converter converts System.DateOnly
to System.DateTime
and System.DateTime
to System.DateOnly
.
Here is the converter definition in XAML:
<telerik:DateOnlyToDateTimeConverter x:Key="DateOnlyToDateTimeConverter" />
The following example demonstrates how to set DateOnly
in the DatePicker using a converter.
1. Define the control and the properties:
<VerticalStackLayout WidthRequest="300" HorizontalOptions="Center">
<VerticalStackLayout.BindingContext>
<local:ViewModel />
</VerticalStackLayout.BindingContext>
<telerik:RadDatePicker x:Name="datePicker"
MinimumDate="{Binding MinimumDate, Converter={StaticResource DateOnlyToDateTimeConverter}}"
DefaultHighlightedDate="{Binding DefaultHighlightedDate, Converter={StaticResource DateOnlyToDateTimeConverter}}"
Date="{Binding SelectedDate, Mode=TwoWay, Converter={StaticResource DateOnlyToDateTimeConverter}}"
MaximumDate="{Binding MaximumDate, Converter={StaticResource DateOnlyToDateTimeConverter}}"
WidthRequest="{OnPlatform MacCatalyst=300, WinUI=300}"
HorizontalOptions="{OnPlatform MacCatalyst=Center, WinUI=Center}" />
</VerticalStackLayout>
2. Define the converter in the Page's resource:
<telerik:DateOnlyToDateTimeConverter x:Key="DateOnlyToDateTimeConverter" />
3. Add the telerik
namespace:
xmlns:telerik="http://schemas.telerik.com/2022/xaml/maui"
4. Add the ViewModel
:
public class ViewModel : NotifyPropertyChangedBase
{
private DateOnly? selectedDate;
public ViewModel()
{
this.MinimumDate = new DateOnly(2020, 1, 1);
this.DefaultHighlightedDate = new DateOnly(2024, 11, 20);
this.SelectedDate = new DateOnly(2024, 11, 23);
this.MaximumDate = new DateOnly(2028, 12, 31);
}
public DateOnly MinimumDate { get; set; }
public DateOnly DefaultHighlightedDate { get; set; }
public DateOnly? SelectedDate
{
get => this.selectedDate;
set => this.UpdateValue(ref this.selectedDate, value);
}
public DateOnly MaximumDate { get; set; }
}
For the DatePicker DateOnly example, go to the SDKBrowser Demo Application and navigate to the DatePicker > DateOnly category.