CustomEditable Date picker which accepts null value in xamarin forms?

Hruday 1 Reputation point
2021-07-23T13:08:02.333+00:00

How to Implement Editable date picker which allows null in xamarin forms

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,368 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 77,806 Reputation points Microsoft Vendor
    2021-07-26T08:42:20.09+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    You can try inheriting from the DatePicker and adding a property that can be bound to DateTime? type. See the code below. In this case you can bind to NullableDate property instead of Date.

       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;  
               }  
           }  
    

    You can use it in the xaml directly.

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

    Then set it to null in the background code.

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

    Best Regards,

    Leon Lu


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.