Home > Mobile >  How to create nullable DatePickerControl?
How to create nullable DatePickerControl?

Time:12-29

I trying to use .NET MAUI's date picker control in my app. I have a requirement that initially when screen get displayed need to show nothing or "-" below StartDate label. But datepicker control is showing default value like 01/01/1900.

Now, the question is how to modify a datepicker control that it will not show any default value initially?

I have did it using label control above the datepicker inside grid. But that is work around with different control. How to handle this using DatePicker control it self? Is it possible?

CodePudding user response:

Maybe like this .

public class MyDatePicker : DatePicker
{
    private string _format = null;
    public static readonly BindableProperty NullableDateProperty = BindableProperty.Create<MyDatePicker, DateTime?>(p => p.NullableDate, null);
    public DateTime? NullableDate
    {
        get { return (DateTime?)GetValue(NullableDateProperty); }
        set { SetValue(NullableDateProperty, value); UpdateDate(); }
    }
    private void UpdateDate()
    {
        if (NullableDate.HasValue) { if (null != _format) Format = _format; Date = NullableDate.Value; }
        else { _format = Format; Format = "pick ..."; }
    }
    protected override void OnBindingContextChanged()
    {
        base.OnBindingContextChanged();
        UpdateDate();
    }
    protected override void OnPropertyChanged(string propertyName = null)
    {
        base.OnPropertyChanged(propertyName);
        if (propertyName == "Date") NullableDate = Date;
    }
}

In Xaml

<local:MyDatePicker x:Name="myDatePicker"></local:MyDatePicker>

In MainPage.cs

{
        InitializeComponent();
        myDatePicker.NullableDate = null;
    }

CodePudding user response:

In Maui, the DatePicker field can be null, which is a feature that needs to be enhanced. Someone submitted an application on GitHub, you can follow it: [Enhancement] DatePicker and TimePicker should support DateOnly? and TimeOnly?

  • Related