如何在 WPF DataGrid 中动态生成列? [英] How do I dynamically generate columns in a WPF DataGrid?

查看:32
本文介绍了如何在 WPF DataGrid 中动态生成列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 WPF 数据网格中显示查询结果.我绑定的 ItemsSource 类型是 IEnumerable.由于返回的字段直到运行时才确定,因此在评估查询之前我不知道数据的类型.每个行"都作为 ExpandoObject 返回,并具有表示字段的动态属性.

I am attempting to display the results of a query in a WPF datagrid. The ItemsSource type I am binding to is IEnumerable<dynamic>. As the fields returned are not determined until runtime I don't know the type of the data until the query is evaluated. Each "row" is returned as an ExpandoObject with dynamic properties representing the fields.

我希望 AutoGenerateColumns(如下所示)能够像使用静态类型一样从 ExpandoObject 生成列,但它似乎没有.

It was my hope that AutoGenerateColumns (like below) would be able to generate columns from an ExpandoObject like it does with a static type but it does not appear to.

<DataGrid AutoGenerateColumns="True" ItemsSource="{Binding Results}"/>

无论如何要以声明方式执行此操作,还是必须使用某些 C# 进行命令式挂钩?

Is there anyway to do this declaratively or do I have to hook in imperatively with some C#?

编辑

好的,这将为我提供正确的列:

Ok this will get me the correct columns:

// ExpandoObject implements IDictionary<string,object> 
IEnumerable<IDictionary<string, object>> rows = dataGrid1.ItemsSource.OfType<IDictionary<string, object>>();
IEnumerable<string> columns = rows.SelectMany(d => d.Keys).Distinct(StringComparer.OrdinalIgnoreCase);
foreach (string s in columns)
    dataGrid1.Columns.Add(new DataGridTextColumn { Header = s });

所以现在只需要弄清楚如何将列绑定到 IDictionary 值.

So now just need to figure out how to bind the columns to the IDictionary values.

推荐答案

最终我需要做两件事:

  1. 从查询返回的属性列表中手动生成列
  2. 设置数据绑定对象

此后,内置数据绑定启动并运行良好,并且从 ExpandoObject 中获取属性值似乎没有任何问题.

After that the built-in data binding kicked in and worked fine and didn't seem to have any issue getting the property values out of the ExpandoObject.

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Results}" />

// Since there is no guarantee that all the ExpandoObjects have the 
// same set of properties, get the complete list of distinct property names
// - this represents the list of columns
var rows = dataGrid1.ItemsSource.OfType<IDictionary<string, object>>();
var columns = rows.SelectMany(d => d.Keys).Distinct(StringComparer.OrdinalIgnoreCase);

foreach (string text in columns)
{
    // now set up a column and binding for each property
    var column = new DataGridTextColumn 
    {
        Header = text,
        Binding = new Binding(text)
    };

    dataGrid1.Columns.Add(column);
}

这篇关于如何在 WPF DataGrid 中动态生成列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆