将行添加到WPF数据网格中,直到运行时才知道列

我正在尝试向数据网格添加数据(事实上,任何在网格中显示数据的控件都会这样做),但是直到运行时才会知道列(名称和数字)。

我知道如何创建的列:例如

DataGridTextColumn textColumn = new DataGridTextColumn(); textColumn.Header = column.DisplayName; MyDataGrid.Columns.Add(textColumn); 

但是我该如何添加行? 我没有看到如何使用绑定,因为我的数据不包含在具有已知属性的对象中。 例如,每行的数据可能以字符串[]的forms出现。 所以有一次我可能有三列,另一次我可能有五列。

我当时希望能够做到这样的事情:

 // Example data to represent a single row. string[] row1 = new[] { "value1", "value2", "value3" }; var row = new Row; row.AddCell(row1[0]); row.AddCell(row1[1]); row.AddCell(row1[2]); MyDataGrid.Rows.Add(row); 

我必须开始在VS中插入以获得我的头部确切的代码,但是您很可能只是创建列并使用列键作为绑定表达式,因为索引绑定在WPF中起作用

我会在一分钟内得到一些代码 – 但它看起来就像你的行创建代码,但在列上的绑定看起来像(原谅可能不正确的方法名称)

 textColumn.Bindings.Add(new Binding("this[" + columnIndex.ToString() + "]")); 

更新:

是的,不确定这是否是您正在寻找但它的工作原理:

在其上创建了一个带有数据网格的窗口(dataGrid1)

  public MainWindow() { InitializeComponent(); var col = new DataGridTextColumn(); col.Header = "Column1"; col.Binding = new Binding("[0]"); dataGrid1.Columns.Add(col); col = new DataGridTextColumn(); col.Header = "Column2"; col.Binding = new Binding("[1]"); dataGrid1.Columns.Add(col); col = new DataGridTextColumn(); col.Header = "Column3"; col.Binding = new Binding("[2]"); dataGrid1.Columns.Add(col); //dataGrid1.ad List rows = new List(); string[] value; value = new string[3]; value[0] = "hello"; value[1] = "world"; value[2] = "the end"; rows.Add(value); dataGrid1.ItemsSource = rows; } 

例

没有玩过很多数据网格,但你可以试试这样的东西

 int currentRow = MyDataGrid.Rows.Add(); MyDataGrid.Rows[currentRow].Cells[0].Value = row1[0]; MyDataGrid.Rows[currentRow].Cells[1].Value = row1[1]; MyDataGrid.Rows[currentRow].Cells[2].Value = row1[2];