title: How do I dynamically generate columns in a WPF DataGrid?
body: <p>I am attempting to display the results of a query in a WPF datagrid. The ItemsSource type I am binding to is <code>IEnumerable&lt;dynamic&gt;</code>. 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 <code>ExpandoObject</code> with dynamic properties representing the fields.</p>
  
  <p>It was my hope that <code>AutoGenerateColumns</code> (like below) would be able to generate columns from an <code>ExpandoObject</code> like it does with a static type but it does not appear to.</p>
  
  <pre><code>&lt;DataGrid AutoGenerateColumns="True" ItemsSource="{Binding Results}"/&gt;
  </code></pre>
  
  <p>Is there anyway to do this declaratively or do I have to hook in imperatively with some C#?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Ok this will get me the correct columns:</p>
  
  <pre><code>// ExpandoObject implements IDictionary&lt;string,object&gt; 
  IEnumerable&lt;IDictionary&lt;string, object&gt;&gt; rows = dataGrid1.ItemsSource.OfType&lt;IDictionary&lt;string, object&gt;&gt;();
  IEnumerable&lt;string&gt; columns = rows.SelectMany(d =&gt; d.Keys).Distinct(StringComparer.OrdinalIgnoreCase);
  foreach (string s in columns)
      dataGrid1.Columns.Add(new DataGridTextColumn { Header = s });
  </code></pre>
  
  <p>So now just need to figure out how to bind the columns to the IDictionary values.</p>