首页 > 解决方案 > 当有一个 C++/CX 项目时,有没有办法为 CalendarDatePicker 设置默认日期?

问题描述

我有一个 C++/CX UWP 项目,并希望用户从我使用 Windows.UI.Xaml.Controls 创建的 CalendarDatePicker 中选择一个日期。但是,在初始化时,我希望 CalendarDatePicker 选择特定日期(目前没有选择日期,它只是说“选择一个日期”)。我知道这很容易用 C# 实现,而且我很确定 C++ 也有一种方法,但我还没有找到解决方案。

有谁知道如何做到这一点?

标签: c++xamluwpc++-cx

解决方案


您可以将具体日期传递给datePicker->Date。完整的步骤如下。该文档解释了C++/CX中DateTime的相关使用。所以我们可以通过SYSTEMTIME->FILETIME->_ULARGE_INTEGER->DateTime获取DateTime。首先,我们使用COleDateTime类来解析具体的日期字符串(使用前包括ATLComTime.h)和然后转换。

#include <ATLComTime.h>

//parse date string
COleDateTime coDT;
coDT.ParseDateTime(L"2012-11-10", 0, 0); 

//get system time struct​
SYSTEMTIME st;​
coDT.GetAsSystemTime(st);​
​
//COleDateTime is in local timezone, DateTime is in UTC, so we need to convert​
SYSTEMTIME st_utc;​
TzSpecificLocalTimeToSystemTime(nullptr, &st, &st_utc);​
​
//get filetime struct to get a time format compatible with DateTime​
FILETIME fileTime;​
SystemTimeToFileTime(&st_utc, &ft);​
​
//use _ULARGE_INTEGER to get a int64 to set the DateTime struct to​
_ULARGE_INTEGER ulint = { fileTime.dwLowDateTime, fileTime.dwHighDateTime };​
​
Windows::Foundation::DateTime myDateTime;​
wfdt.UniversalTime = ulint.QuadPart;​

//set date
MyDatePicker->Date = myDateTime;

推荐阅读