如何在 wpf 中将新行添加到数据网格中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24095172/
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
How i can add new row into datagrid in wpf?
提问by Mahmoud Samy
I'm trying to Insert all Rows values of DataGrid for Once every Click of a button , so if user inserted three times display on datagrid three rows,I have a class there is code
我正在尝试为每次单击按钮一次插入 DataGrid 的所有行值,因此如果用户插入三次显示在数据网格三行上,我有一个类有代码
public string Name { get; set; }
public string Job { get; set; }
public string Phone { get; set; }
public MyGrid(string Vendors,string Jobs,string Tel)
{
Name = Vendors;
Job = Jobs;
Phone = Tel;
}
and i called into button click event here
我在这里调用了按钮单击事件
static List<MyGrid> gride;
gride = new List<MyGrid>();
for (int i = 0; i < 3; i++)
{
var myg1 = new MyGrid(textBox10.Text, textBox11.Text, textBox12.Text);
gride.Add(myg1);
}
dataGridView1.ItemsSource = gride;
this code it's working but there is the one problem,When add data is supposed to appear in a one row, but appears within 3 rows in the one click , I want to show one row in per click with different data . How i can add new row per click on the button in wpf
这段代码正在运行,但有一个问题,当添加数据应该出现在一行中,但在一次单击中出现在 3 行内时,我想在每次单击中显示一行,其中包含不同的数据。我如何每次点击 wpf 中的按钮添加新行
采纳答案by Rohit Vats
First of all this is not a way to do WPF way. Use proper bindings to achieve you want.
首先,这不是 WPF 的一种方式。使用适当的绑定来实现你想要的。
Steps to do in WPF way:
以 WPF 方式执行的步骤:
- Create
ObservableCollection<MyGrid>and bind ItemsSource with that collection. - Instead of setting ItemsSource again simply add object in that collection. DataGrid will be refreshed automatically since ObservableCollection implement
INotifyCollectionChanged.
ObservableCollection<MyGrid>使用该集合创建和绑定 ItemsSource。- 无需再次设置 ItemsSource,只需在该集合中添加对象即可。自 ObservableCollection 实施后,DataGrid 将自动刷新
INotifyCollectionChanged。
Now, for your code there are couple of issues.
现在,对于您的代码,存在几个问题。
- If you want item to be added once, why to run for loop and add object thrice.
Remove the for loop. - With every button click, you are re-initializing the list. Instead keep the list as instance field and
initialize list only once from class constructor. No need to set ItemsSource againwith every button click.
- 如果您希望项目添加一次,为什么要运行 for 循环并添加对象三次。
Remove the for loop. - 每次单击按钮时,您都在重新初始化列表。而是将列表保留为实例字段和
initialize list only once from class constructor。 No need to set ItemsSource again每次点击按钮。
public class CodeBehindClass
{
private ObservableCollection<MyGrid> gride;
public CodeBehindClass()
{
gride = new ObservableCollection<MyGrid>();
dataGridView1.ItemsSource = gride;
}
private void ButtonHandler(object sender, RoutedEventArgs e)
{
var myg1 = new MyGrid(textBox10.Text, textBox11.Text, textBox12.Text);
gride.Add(myg1);
}
}

