7

我正在尝试为 Windows 8.1 使用新的 dateTimePicker:

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

每当我更改日期时,我在查看 personDOB 的值时都没有得到我选择的值。personDOB 是 DateTimeOffset 类型

我需要做什么才能获得我选择的价值?

更新:

    <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}"/>
4

2 回答 2

12

我从这个链接中找到了答案:

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

您需要编写一个转换器才能使其正常工作:

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;
        }
    }
}
于 2013-10-06T21:01:02.013 回答
1

正如向我解释的那样,最好在转换时抛出异常然后使用默认值。

public class DateTimeToDateTimeOffsetConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return new DateTimeOffset((DateTime)value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return ((DateTimeOffset)value).DateTime;
    }
}
于 2014-04-28T19:16:35.383 回答