Adding rows to a WPF datagrid where columns are not known until runtime

吃可爱长大的小学妹 提交于 2019-12-06 00:26:12

问题


I'm trying to add data to a datagrid (in fact, any control that presents data in a grid will do), but the columns (both names and numbers) are not known until runtime.

The columns I DO know how to create: E.g

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

But how do I add rows? I don't see how I can use binding because my data is not contained in an object with known properties. For example, data for each row might come in as a string[]. So one time I might have three columns, another time I might have five.

I was expecting do be able to do something like this:

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

回答1:


I'd have to start plugging away in VS to get my head round the exact code, but you can most likely just create your columns and use the column key as the binding expression seeing as indexed bindings work in WPF

I'll get some code up in a minute - but it would look something like your row creation code but with bindings on the columns that look something like (forgive the possibly incorrect method names)

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

Update:

Yeah not sure if this is what you are looking for but it works:

Created a single window with a datagrid on it (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;
    }




回答2:


Haven't played with datagrids a lot but you can try something like this

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];


来源:https://stackoverflow.com/questions/10650985/adding-rows-to-a-wpf-datagrid-where-columns-are-not-known-until-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!