将行添加到WPF数据网格,其中列在运行时不知道 [英] Adding rows to a WPF datagrid where columns are not known until runtime

查看:193
本文介绍了将行添加到WPF数据网格,其中列在运行时不知道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向datagrid添加数据(实际上,任何在网格中显示数据的控件都可以),但是列(名称和数字)在运行时才是不知道的。

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.

我期待能够做到这样:

// 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中工作

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() + "]"));

更新:

这是你正在寻找,但它的作品:

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

创建一个单一的窗口,其上有一个datagrid(dataGrid1)

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

这篇关于将行添加到WPF数据网格,其中列在运行时不知道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆