如何为TimePicker设置空值?

问题描述 投票:0回答:1

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

<TimePicker x:Name="timepicker" />
xamarin xamarin.forms timepicker
1个回答
0
投票

你必须创建自己的TimePicker类,允许在XAML上使用NullableTime

该课程应如下:

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}" />

如果您使用此示例,您将看到应该选择默认值...

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.