如何给 TimePicker 设置一个空值?

How to set a null value to TimePicker?

我使用 TimePicker 并以默认值“12:00 AM”显示,我想将该字段设置为空白。

<TimePicker x:Name="timepicker" />

您必须创建自己的 class of TimePicker,这将允许 XAML 上的 NullableTime

Class 应该如下:

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

然后在 XAML 你应该创建你的控件并按如下方式使用它:

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

如果您使用此示例,您会看到默认值应该是 pick...