C++/Winrt学习笔记
ListView的ItemSource
WinRT的ListView是从ItemsControl派生出来的,其ItemSource也是来自于ItemsControl。
对于C++/WinRT而言,需要一堆的接口才能符合ItemSource的要求。
- 序列访问
- IIterable
- IBindableIterable
- 随机访问
- IVector
- IVectorView
- IBindableVector
- IBindableVectorView
- 改动观测
- IObservableVector
[Collections with C++/WinRT]
这一章所列的内容可以帮助实现符合ItemSource的接口。首先winrt::single_threaded_vector可以返回IVector接口,下列是代码示意:
winrt::init_apartment(); // 在MTA初始化线程,并随之初始化COM
Windows::Foundation::Collections::IVector<int> coll{ winrt::single_threaded_vector<int>() };
coll.Append(1);
coll.Append(2);
coll.Append(3);
Windows::Foundation::Collections::IVectorView<int> view{ coll.GetView() };
// 与std::vector的互操作
auto coll1{ winrt::single_threaded_vector<int>({ 1,2,3 }) };
std::vector<int> values{ 1,2,3 };
auto coll2{ winrt::single_threaded_vector<int>(std::move(values)) };
XAML items controls; bind to a C++/WinRT包含一个例子说明如何使用winrt::single_threaded_vector。
winrt::clock struct (C++/WinRT)
查看winrt::clock struct (C++/WinRT)的说明文档,有几点令我惊奇。一是Windows.Foundation.DateTime竟然是投射到std::chrono::time_point,另外就是WinRT采用的Epoch竟然是 Jan 1 1601,而且具有百纳秒级别的精度以及64为的范围。
来看看cock的子类型:
- clock::rep A synonym for int64_t.
- clock::period A synonym for Windows::Foundation::TimeSpan::period.
- clock::duration A synonym for Windows::Foundation::TimeSpan.
- clock::time_point A synonym for Windows::Foundation::DateTime.
作为Windows.Foundation中的一员,DateTime可以通过PropertyValue.CreateDateTime(DateTime) Method转成Property,从Property出来,使用的则是IPropertyValue.GetDateTime Method。
Windows.Foundation中有另外一个接口:IReference<T>
,也可以把相当数目的类型转化为Property。winrt::box_value的底层就是用这个接口的吧。
winrt::box_value返回的是IInspectable。如果value是直接从IInspectable派生出来的,则直接返回。否则通过
IReference<T>
包装以后返回。
如果想在XAML的{x:bind}中使用DateTime类型的值,需要自己写一个Converter,实现IValueConverter,把DateTime值转化为hstring,具体参考Formatting or converting data values for display。
需要在{x:bind}或者{binding}标记扩展中指定Converter,参考Binding.Converter Property 以及https://docs.microsoft.com/en-us/windows/uwp/xaml-platform/x-bind-markup-extension
更多参考:
- https://stackoverflow.com/questions/34713126/stringformat-on-binding
- https://stackoverflow.com/questions/34026332/string-format-using-uwp-and-xbind/34026544
- https://stackoverflow.com/questions/35200838/xbind-converter-and-fallbackvalue-not-collaborating-uwp-10
如果需要格式化DateTime,那么需要使用DateTimeFormatter Class。
如果要在C++中处理各种不同的日历,比如Julian Date,HowardHinnant/date可以提供帮助。
- Handling Julian dates in C++11/14
- proleptic Gregorian calendar
- A better date and time C++ library
- http://howardhinnant.github.io/date_algorithms.html
(本篇完)