Il controllo DatePicker di Xamarin.Forms funziona bene ma non supporta il data-binding a oggetti di tipo Nullable<DateTime>.
Ovviamente la problematica è cara a molte persone
In questo thread nei forum di Xamarin ci sono diverse soluzioni, a fattor comune tutte aggiungono una bindable property chiamata NullableDate a un controllo che eredita da DatePicker e alla quale poi si fa binding e che conterrà l'effettivo valore della proprietà Date esistente. Tra le varie soluzioni proposte nel thread, io mi sono trovato bene con quella che vi riporto:
public class CustomDatePicker : DatePicker
{
private string _format = null;
public static readonly BindableProperty NullableDateProperty = BindableProperty.Create<CustomDatePicker, DateTime?>(p => p.NullableDate, null);
public DateTime? NullableDate
{
get { return (DateTime?)GetValue(NullableDateProperty); }
set { SetValue(NullableDateProperty, value); UpdateDate(); }
}
public static readonly BindableProperty DateFormatProperty = BindableProperty.Create<CustomDatePicker, string>(p => p.DateFormat,
defaultValue: default(string),
defaultBindingMode: BindingMode.OneWay,
propertyChanging: (bindable, oldValue, newValue) =>
{
var ctrl = (CustomDatePicker)bindable;
ctrl.DateFormat = newValue;
});
public string DateFormat
{
get { return (string)GetValue(DateFormatProperty); }
set { SetValue(DateFormatProperty, value); }
}
private void UpdateDate()
{
if (NullableDate.HasValue)
{
Format = DateFormat;
Date = NullableDate.Value;
}
else
{
_format = Format;
Format = "...";
}
}
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
UpdateDate();
}
protected override void OnPropertyChanged(string propertyName = null)
{
base.OnPropertyChanged(propertyName);
if (propertyName == "Date")
NullableDate = Date;
}
}
Non dovrete far altro che aggiungere il solito namespace XML per referenziarlo e utilizzarlo nello XAML, lo utilizzerete esattamente come il DatePicker ma il binding lo farete a NullableDate invece che a Date e la formattazione sarà fatta con DateFormat invece che Format.
Alessandro