将日期绑定到 DatePicker 在 UWP 中不起作用

Har*_*ala 0 c# xaml datepicker uwp

我有一个 DateTime 数据类型变量,它绑定到一个日期选择器。

日期选择器 XAML:

<CalendarDatePicker Name="dpDate" VerticalAlignment="Center" 
         Date="{Binding dpDateTime, ElementName=this, Mode=TwoWay}"
         DateChanged="dp_DateChanged">
</CalendarDatePicker>
Run Code Online (Sandbox Code Playgroud)

后面的代码,它设置值:

dpDatetime = DateTime.Now;
Run Code Online (Sandbox Code Playgroud)

但是 datepicker 没有选择当前日期,而是将日期选择为 1/1/1917

Mar*_*und 5

问题是您设置的日期属于类型,DateTime而日历需要DateTimeOffset.

您可以通过将您的dpDateTime属性类型更改为DateTimeOffset.

总的来说,最好使用DateTimeOffset而不是DateTime无处不在,因为它包含时区信息,当用户的时区更改时,这使您的代码更可靠。

更新 - INotifyPropertyChanged

您还必须实施INotifyPropertyChanged以便将值更改通知给数据绑定。首先,您必须INotifyPropertyChanged在类中添加实现接口:

public class Page : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    // This method is called by the Set accessor of each property.
    // The CallerMemberName attribute that is applied to the optional propertyName
    // parameter causes the property name of the caller to be substituted as an argument.
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

然后更新属性设置器以使用设置器:

private DateTimeOffset _dpDateTime = DateTime.Now;

public DateTimeOffset dpDateTime
{
   get { return _dpDateTime; }
   set 
   {  
       _dpDateTime = value;
       NotifyPropertyChanged();
   }
}
Run Code Online (Sandbox Code Playgroud)

数据绑定功能需要目标属性引发PropertyChanged事件,因为幕后的数据绑定会观察此事件。