【问题标题】:datetimepicker binding issues日期时间选择器绑定问题
【发布时间】:2013-10-07 01:20:02
【问题描述】:

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

【问题讨论】:

  • 你设置DataContext了吗?
  • @Xyroid - 是的,我已经做到了。
  • 检查datepicker的datacontext是否为空。
  • 里面有数据。从表面上看,它也有正确的日期。但我的绑定仍然显示 1/1/0001
  • @Xyroid - 查看我更新的问题

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


【解决方案1】:

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

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

【讨论】:

  • 永远不要在逻辑流中使用 try/catch!用 if/else 替换它。在这种情况下if(value is DateTime) { ... } else { ... }
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 2011-12-02
    相关资源
    最近更新 更多