Search code examples
windows-8winrt-xamldatetimepickerwindows-8.1

datetimepicker binding issues


I'm trying to use the new dateTimePicker for Windows 8.1:

<DatePicker HorizontalAlignment="Left" Margin="401,245,0,0" Grid.Row="1"
 VerticalAlignment="Top" Width="352" Date="{Binding personSingle.personDOB,Mode=TwoWay}"/>

When ever I change the date I don't get the value that I chose when I look at value for personDOB. personDOB is of type DateTimeOffset

What do I need to do get the value that I choose?

Update:

    <DatePicker x:Name="dtPick" HorizontalAlignment="Left" Margin="401,245,0,0" Grid.Row="1" 
VerticalAlignment="Top" Width="352" DataContext="{Binding personSingle}"
 Date="{Binding personSingle.personDOB.Date,Mode=TwoWay}"/>

Solution

  • I found the answer from this link:

    http://bretstateham.com/binding-to-the-new-xaml-datepicker-and-timepicker-controls-to-the-same-datetime-value/

    You need to write a converter to get this to work appropriately:

    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;
            }
        }
    }