是否可以在WPF中将ListView(不是DataGrid)绑定到事先未知列的Matrix(交叉表)数据集中?
使用Northwind数据库作为示例:下面的简单查询将返回一个可以轻松绑定到列表视图的已知数据集:
SELECT Year(o.OrderDate) AS [Year], Month(o.OrderDate) AS [Month],
COUNT(o.OrderID) AS [NumOrders]
FROM Orders o
GROUP BY Year(o.OrderDate), Month(o.OrderDate)
ORDER BY 1, 2
为了生成更有意义的报告,我们可以从上面的查询(在报告程序中)运行结果集来生成如下所示的内容:
SELECT [Year],
SUM(CASE [Month] WHEN 1 Then NumOrders ELSE 0 END) AS 'Jan',
SUM(CASE [Month] WHEN 2 Then NumOrders ELSE 0 END) AS 'Feb',
SUM(CASE [Month] WHEN 3 Then NumOrders ELSE 0 END) AS 'Mar',
SUM(CASE [Month] WHEN 4 Then NumOrders ELSE 0 END) AS 'Apr',
SUM(CASE [Month] WHEN 5 Then NumOrders ELSE 0 END) AS 'May',
SUM(CASE [Month] WHEN 6 Then NumOrders ELSE 0 END) AS 'Jun',
SUM(CASE [Month] WHEN 7 Then NumOrders ELSE 0 END) AS 'Jul',
SUM(CASE [Month] WHEN 8 Then NumOrders ELSE 0 END) AS 'Aug',
SUM(CASE [Month] WHEN 9 Then NumOrders ELSE 0 END) AS 'Sep',
SUM(CASE [Month] WHEN 10 Then NumOrders ELSE 0 END) AS 'Oct',
SUM(CASE [Month] WHEN 11 Then NumOrders ELSE 0 END) AS 'Nov',
SUM(CASE [Month] WHEN 12 Then NumOrders ELSE 0 END) AS 'Dec'
FROM
(
SELECT Year(o.OrderDate) AS [Year], Month(o.OrderDate) AS [Month],
COUNT(o.OrderID) AS [NumOrders]
FROM Orders o
GROUP BY Year(o.OrderDate), Month(o.OrderDate)
)t0
GROUP BY [Year]
结果如下:
我的问题是,是否可以将此最终结果绑定到WPF中的ListView或Flowdocument,而无需事先了解结果列?
答案 0 :(得分:2)
您可以以编程方式为ListView生成GridViewColumns并将绑定应用于该视图。循环遍历DataSet中的列,并将相应的GridViewColumn添加到ListView中。
var gridView = (GridView)list.View;
foreach(var col in table.Columns) {
gridView.Columns.Add(new GridViewColumn{
Header=col.ColumnName,
DisplayMemberBinding=new Binding(col.ColumnName)});
}
答案 1 :(得分:1)
您可以使用附加属性动态地将列添加到ListView。查看 CodeProject 上的这篇文章,它完全解释了......