Click here to Skip to main content
15,910,471 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
If I generate the columns of a DataGrid at runtime (because the number of columns is not known before) this way:

C#
var i = 0;
foreach (var property in Records[0].Properties)
 {
 var binding = new Binding("Properties[" + i.ToString() + "].Value");
 dg.Columns.Add(new DataGridTextColumn() { Header = <...>, Binding = binding });
 }
 DataContext = this;


where

XML
<DataGrid Name ="dg" AutoGenerateColumns="False" ItemsSource="{Binding Path=Records}" />


this WORKS fine.


-----

On the other hand, if the number of DataGrids is unknown at compile time, and I try to generate them on the fly:


C#
var dg2 = new DataGrid();
  var binding = new Binding("Properties[0].Value");
  var column = new DataGridTextColumn() { Header = "X", Binding = binding };
  dg2.Columns.Add(column);
  DataContext = this;
  var main = ((MainWindow)App.Current.Windows[0]); // I'm in a different class now
  main.Base.Children.Add(dg2);     // Base is the main Grid.



then it doesn't work (It just shows the header, no data). Any ideas? Thanks!!
Posted
Comments
Szymon Roslowski 29-Jan-14 12:15pm    
Wouldn't setting AutoGenerateColumns="true" solve your problem ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900