如何在WPF中的数据网格中添加和绑定列?

问题描述:

您好,



我想在WPF中的数据网格中手动添加列。



所以,如何在WPF DataGrid中添加和绑定列,就像简单的Windows应用程序一样?



请帮帮我。



在此先感谢。



Ankit Agarwal

软件工程师

Hello,

I want to add column manually in datagrid in WPF.

So, How to add and bind column in WPF DataGrid like simple windows application?

Please help me.

Thanks in Advance.

Ankit Agarwal
Software Engineer

这可以通过定义数据网格的对象数据源并操纵数据源值来自动反映数据网格来完成



参考本文例如

绑定对象数据源









否则,如果您希望将集合的代码绑定绑定到datagrid,那么下面链接中提到的示例将提供你的详细信息

绑定集合

This can be done either by defining a object datasource to the datagrid and manipulating the datasource value towill be reflected in data grid automatically

Refer to this article for example
binding object data source




Else if you prefer codewise binding of a collection to datagrid then the example mentioned in below link will provide you the details
binding collection


private void AddColumn_Click(object sender, RoutedEventArgs e)
    {
      dt.Columns.Add(new DataColumn("New Column" + newColumnIndex++));
      for (int i = 0; i < dt.Rows.Count; i++)
      {
        dt.Rows[i][dt.Columns.Count - 1] = i.ToString() + " - New Column";
      }

      // Refresh the DataGrid
      dataGrid.ItemsSource = null;
      dataGrid.ItemsSource = dt.DefaultView;
    }