WinUI3中如何通过代码获取TimePicker控件的SelectedTime文本值
解决WinUI 3 TimePicker获取"HH:mm"格式时间文本的问题
你的问题在于SelectedTime属性返回的是IReference<TimeSpan>类型(可空的TimeSpan),直接将其装箱显示只会输出类型名称,而非格式化后的时间字符串。以下是正确的实现方式:
修改后的C++代码
#include <format> #include <winrt/Windows.Foundation.h> void MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&) { auto selectedTime = Control2().SelectedTime(); if (selectedTime) // 检查是否有选中的时间 { winrt::Windows::Foundation::TimeSpan timeSpan = selectedTime.Value(); // 提取小时和分钟,格式化为"HH:mm" std::wstring timeStr = std::format(L"{:02d}:{:02d}", timeSpan.Hours(), timeSpan.Minutes()); myButton().Content(box_value(timeStr)); } else { // 处理未选中时间的情况 myButton().Content(box_value(L"No time selected")); } }
关键说明
selectedTime是可空类型,需要先通过if (selectedTime)判断是否存在有效值,再调用Value()获取实际的TimeSpan对象TimeSpan的Hours()和Minutes()方法可以直接提取小时和分钟数值- 使用
std::format(C++20及以上支持)将数值格式化为两位数字的小时和分钟,确保像"09:05"这样的格式正确 - 若你的项目不支持C++20,也可以用
swprintf来拼接字符串:wchar_t timeBuf[6]; swprintf(timeBuf, sizeof(timeBuf)/sizeof(wchar_t), L"%02d:%02d", timeSpan.Hours(), timeSpan.Minutes()); std::wstring timeStr(timeBuf);
为什么之前的代码会崩溃
selectedTime.GetString()是错误的调用,因为IReference<TimeSpan>并非字符串类型的引用,该方法仅适用于IReference<hstring>类型,直接调用会导致未定义行为(程序崩溃)。
内容的提问来源于stack exchange,提问作者Zend
相关产品推荐
相关产品推荐

