Ir al contenido principal

Entradas

Mostrando entradas de marzo, 2018

x:Bind DateTime to DatePicker (DateTimeOffset conversion)

If you need to bind a DateTime property you have in your ViewModel with a DatePicker in your XAML, all you must to do is implement a converter.
Below you can see the Converter class:

...
    public class DateTimeToPickerConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var date = (DateTime)value;
            return new DateTimeOffset(date);
        }
        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
...

and here you can see the XAML markup:

...


<Page.Resources>
<co:DateTimeToPickerConverter x:Key="DateTimeToPickerConverter"/>
</Page.Resources> ...

<DatePicker Date="{x:Bind ManufacturedDate, Converter={StaticResource DateTimeToPickerConverter}}"/>