以编程方式向 WPF DataGrid 添加新行

Programmatically add new row to WPF DataGrid

我试图在单击特定按钮时向 WPF 应用程序上的 DataGrid 添加新行。 这是我到目前为止尝试过的:

DataGridRow row = new DataGridRow();
table.Items.Add(row); // table = my DataGrid

当我 运行 这段代码时,它抛出一个 System.ArgumentNullException

Value cannot be null

我应该怎么做才能解决这个问题? 提前致谢。

您需要将数据网格的 ItemsSource 属性 绑定到 POCO 对象的集合,而不是添加数据网格行,而是将新的 POCO 对象添加到该集合,您的 "problem" 将自动解决...

这假定您的 VM 属性发生更改通知并在您的 POCO 类 中实施 INotifyPropertyChanged 当然...