ComponentOne DataGrid for WPF 支持整个表格范围的打印。但并不灵活,往往一些用户需要打印部分表格区域而并非整体。本篇博客即将展示如何通过自定义方法实现区域打印功能。
我们将通过以下步骤完成区域打印功能:
- 创建一个临时过滤数据表,用于展示选择的数据。
- 创建新增 C1DataGrid。
- 绑定临时数据表到新增的 C1DataGrid 控件。
- 打印新增的 C1DataGrid
基本设置
开始实现功能之前,我们需要绑定数据和设置 SelectionMode 属性。绑定数据源到表格控件,你可以参考帮助文档 http://helpcentral.componentone.com/nethelp/c1datagridwpf/#!Documents/step2of3bindingthegr.htm" target="_blank">点击进入。通过
Step I) 创建过滤数据表
1: private DataTable GetTableOfSelectedRange(C1.WPF.DataGrid.C1DataGrid view)
2: {3: // create a table containing the selection range
4: DataTable resultTable = new DataTable();5: DataTable sourceTable = null;6:7: // create lists for selected row & column ranges
8: var rowSel = c1DataGrid1.Selection.SelectedRows.ToList();9: var colSel = c1DataGrid1.Selection.SelectedColumns.ToList();10:11: if (view.ItemsSource is DataView)12: sourceTable = ((DataView)view.ItemsSource).Table;13: if (sourceTable != null)
14: {15: for (int colHandle = 0; colHandle < colSel.Count; colHandle++)16: {17: resultTable.Columns.Add(new DataColumn(colSel[colHandle].Name));
18: }19: for (int rowHandle = 0; rowHandle < rowSel.Count; rowHandle++)20: {21: ArrayList values = new ArrayList();22: for (int colHandle = 0; colHandle < colSel.Count; colHandle++)23: {24: values.Add(colSel[colHandle].GetCellValue(rowSel[rowHandle]));
25: }26: resultTable.Rows.Add(values.ToArray());
27: }28: resultTable.AcceptChanges();29: }30: return resultTable;31: }
Step II) 创建新的 C1DataGrid 控件
1: // Create a CloneGrid
2: C1.WPF.DataGrid.C1DataGrid clonedGrid = new C1DataGrid();3:4: // Add it to the Visual Tree
5: grid1.Children.Add(clonedGrid);
Step III) 绑定过滤数据表到新增的 C1DataGrid 控件
1: // Assign the cloneTable as the Itemsource for the cloneGrid
2: DataTable clonedTable = GetTableOfSelectedRange(c1DataGrid1);3: clonedGrid.ItemsSource = clonedTable.AsDataView();
Step IV) 打印单元格范围
1: //Print the Grid
2: clonedGrid.Print("test");
打印结果效果图如下:
Demo 下载:
VS2010 + Framework4.0 + C# 点击下载
VS2010 + Framework4.0 + VB.NET 点击下载