在 WPF 中向 DataGrid 添加一行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38236435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding A Row To A DataGrid In WPF?
提问by Meme Machine
So in WinForms you can easily add a row, for example
因此,在 WinForms 中,您可以轻松添加一行,例如
dataGridView1.Rows.Add(user.Handle, c);
But in WPF, when I try to use a DataGrid there is no 'Rows' property. Is there any way to do this in WPF that doesn't consist of an insane amount of lines of code or a lot of messing with XAML?
但是在 WPF 中,当我尝试使用 DataGrid 时,没有 'Rows' 属性。有没有办法在 WPF 中做到这一点,而不是由大量的代码行或大量与 XAML 组成的?
采纳答案by ViVi
It's this simple :
这很简单:
// add a row
DataGrid.Items.Add(new DataItem());
// add a column
DataGrid.Columns.Add(new DataGridTextColumn());
Please refer this link for more, http://wpf.codeplex.com/Thread/View.aspx?ThreadId=34065
更多请参考这个链接,http://wpf.codeplex.com/Thread/View.aspx?ThreadId=34065
Or if you don't like to add rows directly like that, use a collection as source. Bind the Grid to a List (Observable collection). Add items to that list. Result: new rows show up in the grid.
或者,如果您不喜欢像这样直接添加行,请使用集合作为源。将网格绑定到列表(可观察集合)。将项目添加到该列表中。 结果:新行显示在网格中。
回答by KillerKidz
if you are not binding it to any source (i.e DataTable, List etc) try
如果您没有将其绑定到任何源(即 DataTable、List 等),请尝试
dataGridView1.Items.Add(new DataItem { Column1 = "a", Column2 = "b" });

