概述
Windows Community Toolkit 4.0 于 2018 月 8 月初发布:Windows Community Toolkit 4.0 Release Note. 4.0 版本相较于 3.0,增加了 DataGrid 等控件,Sample App 支持了 Fluent Design 设计和明暗两种风格,修复了遗留的控件 BUG,接下来我们主要看一下 DataGrid 控件的实现。
DataGrid 控件是一个可以展示多行多列数据集合的控件,相信大家在 Silverlight WPF 等平台开发中都有过接触,该控件非常适合用来展示数据表格,可以完全是文本内容展示,也可以在数据中包含按钮等操作;另外控件还支持筛选,分组等操作需求。
由于 DataGrid 控件涉及到的功能比较复杂,代码量也比较大,我们会分为几篇文章来详细讲解。而本篇,我们会先针对 DataGrid 控件的整体实现和使用做介绍。
下面是 Windows Community Toolkit Sample App 的示例截图和 code/doc 地址:

Windows Community Toolkit Doc - DataGrid
Windows Community Toolkit Source Code - DataGrid
Namespace: Microsoft.Toolkit.Uwp.UI.Controls; Nuget: Microsoft.Toolkit.Uwp.UI.Controls.DataGrid;
开发过程
代码结构分析
本篇我们先对 DataGrid 的整体代码结构做概览分析,后续会分几篇文章来分析每个重要的类和方法实现。来看一下 DataGrid 的代码结构:

可以看到,DataGrid 的代码结构上是一整个 Project,而在 Nuget 上也能体现。接下看一下几个文件夹的组成和其中重要的类:
1. CollectionViews
CollectionViews 是 DataGrid 的数据部分,可以看到 CollectionView 是基类,EnumerableCollectionView 和 ListCollectionView 继承自它,而这两个类分别代表枚举类的集合,以及列表类的集合。这两个类,都会在 DataGrid 获取数据源时被使用到。
2. Utilities
Utilities 是 DataGrid 控件的基础类和帮助类集合,可以看到涉及到绑定,数值相等(接近)判断,扩展功能,索引值映射,键盘帮助类,值范围,类型帮助类,UI 设置帮助类,校验类,可视状态类和内存管理监听类;后面我们会详细讲解每个类的重点实现部分。

3. DataGrid
DataGrid 控件的最重要实现在 DataGrid 文件夹中,一共有 50 多个类。我们可以先看一遍这里类的大致作用,后面会详细讲解每个类的代码实现:
- Automation - DataGrid UIA 实现
- DataGrid,DataGridColumn,DataGridRow,DataGridCell 控件类,控件头,基于这些类的实现类;
- DataGrid,DataGridColumn,DataGridRow,DataGridCell 相关事件处理类;
- DataGrid,DataGridColumn,DataGridRow,DataGridCell 相关数据类;


调用示例
我们来看一下 DataGrid 控件的调用方式,先看一下 XAML 的简单实现:
- xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
- <controls:DataGrid x:Name="dataGrid1"
- Height="600" Margin="12"
- AutoGenerateColumns="True"
- ItemsSource="{x:Bind MyViewModel.Customers}" />
接着看一下数据源的简单代码:
- public class Customer
- {
- public String FirstName { get; set; }
- public String LastName { get; set; }
- public String Address { get; set; }
- public Boolean IsNew { get; set; }
- public Customer(String firstName, String lastName,
- String address, Boolean isNew)
- {
- this.FirstName = firstName;
- this.LastName = lastName;
- this.Address = address;
- this.IsNew = isNew;
- }
- public static List<Customer> Customers()
- {
- return new List<Customer>(new Customer[4] {
- new Customer("A.", "Zero",
- "12 North Third Street, Apartment 45",
- false),
- new Customer("B.", "One",
- "34 West Fifth Street, Apartment 67",
- false),
- new Customer("C.", "Two",
- "56 East Seventh Street, Apartment 89",
- true),
- new Customer("D.", "Three",
- "78 South Ninth Street, Apartment 10",
- true)
- });
- }
- }
看一下运行结果:

总结
到这里我们就把 Windows Community Toolkit 4.0 中的 DataGrid 概览和代码整体结构讲解完成了,希望能对大家更好的理解和使用这个功能有所帮助。后续会对该控件做系列的详细讲解。
最后,再跟大家安利一下 WindowsCommunityToolkit 的官方微博:https://weibo.com/u/6506046490, 大家可以通过微博关注最新动态。
衷心感谢 WindowsCommunityToolkit 的作者们杰出的工作,感谢每一位贡献者,Thank you so much, ALL WindowsCommunityToolkit AUTHORS !!!