datetimepicker绑定问题

时间:2013-10-01 01:56:58

标签: windows-8 winrt-xaml datetimepicker windows-8.1

我正在尝试使用新的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}"/>

当我改变日期时,当我查看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}"/>

2 个答案:

答案 0 :(得分: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;
        }
    }
}

答案 1 :(得分: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;
    }
}