Search code examples
xamarinxamarin.formstimepicker

How to set a null value to TimePicker?


I use the TimePicker and appear with a default value of "12:00 AM", I want to set the field in blank.

<TimePicker x:Name="timepicker" />

Solution

  • You must create your own class of TimePicker that will allow a NullableTime on XAML.

    The Class should be as following:

    public class MyTimePicker : TimePicker
        {
            private string _format = null;
            public static readonly BindableProperty NullableDateProperty = 
            BindableProperty.Create<MyTimePicker, TimeSpan?>(p => p.NullableTime, null);
    
            public TimeSpan? NullableTime
            {
                get { return (TimeSpan?)GetValue(NullableDateProperty); }
                set { SetValue(NullableDateProperty, value); UpdateTime(); }
            }
    
            private void UpdateTime()
            {
                if (NullableTime.HasValue) { if (null != _format) Format = _format; Time = NullableTime.Value; }
                else { _format = Format; Format = "pick ..."; }
            }
            protected override void OnBindingContextChanged()
            {
                base.OnBindingContextChanged();
                UpdateTime();
            }
    
            protected override void OnPropertyChanged(string propertyName = null)
            {
                base.OnPropertyChanged(propertyName);
                if (propertyName == "Time") NullableTime = Time;
            }
        }
    

    Then on XAML you should create your control and use it as below:

    <local:MyTimePicker NullableTime="{x:Null}" />
    

    If you use this sample you will see that the default value should be pick...

    enter image description here