将行添加到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
没有玩过很多数据网格,但你可以试试这样的东西
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];
- 在库和.Net framework 4.6.1中使用.Net Standard 1.4和应用程序时,无法加载文件System.IO.FileSystem,Version = 4.0.1.0
- 限制对只读属性的方法调用的访问
- 运行时创建LINQ表达式
- System.Web.HttpException:不能在DropDownList中选择多个项目
- xna 4.0和加载图像失败
- Castle Windsor – 注入IActionInvoker实施问题
- IFilter提供者和关注点分离
- 可移植类库中的Thread.Sleep()
- 获取/设置注册表ACL“SeSecurityPrivilege”时出现C#随机exception