How do I dynamically generate columns in a WPF DataGrid?

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.

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

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

Leave a Comment