C#WPF如何在不将动态行项绑定到任何类型的情况下将其添加到DataGrid



我正在编写一个基于用户输入创建动态DataGrid的程序,用户只提供列名、行名,基于此,我需要生成允许用户输入值的空DataGrid。但由于我找不到任何适合我的情况的内容,所以我的列将包含数字,并且我无法创建类型来容纳它们。我发现的解决方案只有在创建类型并使用该类型的属性时才有效,但我无法预测我需要多少属性,所以我需要将数组添加为行。

我想要实现的是这样的目标:

private void generate_DataGrid(string[] headers)
{
foreach (string h in headers) {
DataGridTextColumn gridColumn = new DataGridTextColumn();
gridColumn.Header = h;
tabelaDataGrid.Columns.Add(gridColumn);
}
int[] row1 = new int[3];
int[] row2 = new int[3];
tabelaDataGrid.Items.Add(row1);
tabelaDataGrid.Items.Add(row2);
}

上面的解决方案会生成空行,但我无法编辑它们:

"System.InvalidOperationException:此视图不允许使用'EditItem'。'">

或者我应该搜索其他解决方案,比如电子表格库?

您是否尝试将DataGrid绑定到DataTable,然后像这样添加行和列:(请注意,BindableBasePrism框架的一部分;如果不使用它,请搜索INotifyPropertyChanged接口,看看如何从头开始实现它(

public class DataGridExampleViewModel : BindableBase
{
private DataTable _dataTable;
public DataTable DataTable
{
get { return _dataTable; }
set { SetProperty(ref _dataTable, value); }
}
public DataGridExampleViewModel()
{
//Create a empty dataTable
DataTable = new DataTable();
}
//Add a column to the DataTable the Type is optional
public void AddColumn(string columnName, Type dataType)
{
DataTable.Columns.Add(columnName, dataType);
}
//Add an empty row to the DataTable
public void AddRow()
{
//Create a new row
var row = DataTable.NewRow();
//Add the row to the DataTable
DataTable.Rows.Add(row);
}      
}

如果你是WPF的新手,并且不熟悉数据绑定,我强烈建议你去寻找它

旁注:查看Prism&MahApps.Metro都是构建WPF应用程序的优秀库。

最新更新