简体   繁体   English

我如何在WPF中将新行添加到DataGrid中?

[英]How i can add new row into datagrid in wpf?

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的所有Rows值,所以如果用户在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 . 这段代码可以正常工作,但是有一个问题,当添加数据应该显示在一行中,但是一次单击却出现在3行中时,我想用不同的数据在每次单击中显示一行。 How i can add new row per click on the button in wpf 我如何在WPF中单击按钮可以添加新行

First of all this is not a way to do WPF way. 首先这不是做WPF的方法。 Use proper bindings to achieve you want. 使用适当的绑定来实现您想要的。

Steps to do in WPF way: 以WPF方式执行的步骤:

  1. Create ObservableCollection<MyGrid> and bind ItemsSource with that collection. 创建ObservableCollection<MyGrid>并将ItemsSource与该集合绑定。
  2. Instead of setting ItemsSource again simply add object in that collection. 无需再次设置ItemsSource,只需在该集合中添加对象。 DataGrid will be refreshed automatically since ObservableCollection implement INotifyCollectionChanged . 自ObservableCollection实现INotifyCollectionChanged以来,DataGrid将自动刷新。

Now, for your code there are couple of issues. 现在,对于您的代码,有几个问题。

  1. If you want item to be added once, why to run for loop and add object thrice. 如果要一次添加项目,为什么要运行循环并添加对象三次。 Remove the for loop . Remove the for loop
  2. 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 . 而是将列表保留为实例字段,并initialize list only once from class constructor
  3. No need to set ItemsSource again with every button click. No need to set ItemsSource again每次单击按钮都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);
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM