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

时间:2012-05-18 10:32:40

标签: c# wpf datagrid runtime

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

我知道如何创建的栏目:E.g

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

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

我期待能够做到这样的事情:

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

2 个答案:

答案 0 :(得分:13)

我必须开始在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<object> rows = new List<object>();
        string[] value;

        value = new string[3];

        value[0] = "hello";
        value[1] = "world";
        value[2] = "the end";
        rows.Add(value);

        dataGrid1.ItemsSource = rows;
    }

Example

答案 1 :(得分:-1)

没有玩过很多数据网格,但你可以尝试这样的事情

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];
相关问题