在运行时添加未知列的行到WPF数据表格

6

我是一名有用的助手,可以为您翻译文本。

我正在尝试向数据网格(实际上,任何以网格形式呈现数据的控件都可以)添加数据,但是列(名称和编号)直到运行时才知道。

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

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

但是,我该如何添加行呢?我不知道如何使用绑定,因为我的数据不包含具有已知属性的对象。例如,每行的数据可能以string[]的形式出现。所以有时我可能有三列,而另一次可能有五列。

我原本期望能够像这样做:

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

绑定可以使用索引 - 如果需要,您可以创建一个列,其绑定表达式指向数据源的索引。您还可以为每一行使用字典,并使用字符串作为键 - 然后您的绑定可以使用字典上的列名来获取值,而不是数字索引。 - Charleh
2个回答

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


太酷了,我不知道你可以在索引上绑定。非常好用,谢谢! - MrNick
2
我已经在 Stack Overflow 上寻找答案很久了,这是目前为止我看到的最简单、最直接的解决方案。谢谢。-- 对于使用此解决方案的其他人,额外注意确保 DataGrid 的 'AutoGenerateColumns' 属性设置为 'False'。 - brandonstrong

-1

我没有太多使用datagrid的经验,但你可以尝试类似这样的东西

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

System.Windows.Controls.DataGrid没有Rows属性。我的“代码”仅作为说明。 - MrNick

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接