How do I dynamically generate columns in a WPF DataGrid?

后端 未结 4 1718
一生所求
一生所求 2020-12-01 00:55

I am attempting to display the results of a query in a WPF datagrid. The ItemsSource type I am binding to is IEnumerable. As the fields returned

4条回答
  •  时光说笑
    2020-12-01 01:42

    Ultimately I needed to do two things:

    1. Generate the columns manually from the list of properties returned by the query
    2. Set up a DataBinding object

    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.

    
    

    and

    // 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>();
    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);
    }
    

提交回复
热议问题