Caliburn.Micro Binding DateTimeOffset to DatePicker
Asked Answered
H

2

7

I need to bind DateTimeOffset property to a WPF DatePicker since Odata not supports DateTime. I know how to bind DateTime property.

I have tried binding DateTimeOffset property to DatePicker as same as binding DateTime property.

But the value is not changing at all. It's always has the default value.

How can I solve this problem?

Hannigan answered 12/8, 2015 at 15:7 Comment(2)
Convert to a DateTime using DataTimeOffset.DateTime property. As you already know how to bind that, would probably be quicker than figuring out how to bind a DateTimeOffset.Jacelynjacenta
Thanks Jack, it works when saving the record. But i'm getting an error while retriving the record. "A TwoWay or OneWayToSource binding cannot work on the read-only property 'DateTime' of type 'System.DateTimeOffset'.". Do you have any idea?Hannigan
L
4

Try using this value converter.

public class DateTimeToDateTimeOffsetConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
            DateTimeOffset dto = (DateTimeOffset)value;
            return dto.DateTime;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
            DateTime date = (DateTime)value;
            return new DateTimeOffset(date);
    }
}

I based this solution on: http://bretstateham.com/binding-to-the-new-xaml-datepicker-and-timepicker-controls-to-the-same-datetime-value/

Luculent answered 28/9, 2018 at 19:48 Comment(2)
This works beautifully, though the name is backwards. It should be DateTimeOffsetToDateTimeConverter.Newhall
Also, to handle nullables, change the first line to DateTimeOffset ? dto = (DateTimeOffset?) value; and in the convert back add to the beginning if (value == null) return null;Newhall
C
0

Convert it to a DateTime as Jack suggested. To avoid the error you described in the comment, set the BindingMode to OneWay "{Binding Path=MyProperty, Mode=OneWay}"

Culley answered 13/8, 2015 at 7:8 Comment(1)
I agree, but adding binding Mode=OneWay will only set's the value from data-source to UI Element. The changes made in UI Element (DatePicker) will not reflect in DataSource Right? How can i change the date in DatePicker and save it back to DB? And how can i add null value?Hannigan

© 2022 - 2024 — McMap. All rights reserved.