0

I'm triying to bind a DateTime from the ViewModel to a calendarDatePicker, but it doesn't work. i've tried in a textbox and works.

This part works:

<TextBox Text="{Binding MyDate}" ></TextBox>

And this doesn't:

<CalendarDatePicker Date="{Binding MyDate}" />
SamTh3D3v
  • 9,854
  • 3
  • 31
  • 47
El0din
  • 3,208
  • 3
  • 20
  • 31

1 Answers1

2

This question was previously answered here on MSDN.

Per the article, you could use a Converter to convert the binding to a DateTimeOffset. The converter may look something like the following, which comes from this post (referenced by the MSDN answer):

public class DateTimeToDateTimeOffsetConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        try
        {
            DateTime date = (DateTime)value;
            return new DateTimeOffset(date);
        }
        catch (Exception ex)
        {
            return DateTimeOffset.MinValue;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        try
        {
            DateTimeOffset dto = (DateTimeOffset)value;
            return dto.DateTime;
        }
        catch (Exception ex)
        {
            return DateTime.MinValue;
        }
    }
}
BlueTriangles
  • 1,124
  • 2
  • 13
  • 26
  • Works, Date ="{Binding MyDate, Mode=TwoWay ,Converter={StaticResource DateTimeToDateTimeOffset}}" – El0din Feb 21 '18 at 09:29