迭代WPF Datagrid中的所有单元格

时间:2012-11-19 06:57:42

标签: c# wpf datagrid

  

可能重复:
  WPF DataGrid: How do you iterate in a DataGrid to get rows and columns?

我有WPF DataGrid。我想迭代cells中的所有Datagrid。 给我一个简单的代码来做到这一点。  喜欢这个

for(int i =0 ....) //rows
{
    for(int j=0 ....) //columns
    {
        //access cell
    }
}

1 个答案:

答案 0 :(得分:3)

 public IEnumerable<Microsoft.Windows.Controls.DataGridRow> GetDataGridRows(Microsoft.Windows.Controls.DataGrid grid)
 {
     var itemsSource = grid.ItemsSource as IEnumerable;
     if (null == itemsSource) yield return null;
     foreach (var item in itemsSource)
     {
        var row = grid.ItemContainerGenerator.ContainerFromItem(item) as Microsoft.Windows.Controls.DataGridRow;
                if (null != row) yield return row;
      }
 }

//假设网格绑定到某些信息类的可观察集合

foreach (DataGridRow rowContainer  in GetDataGridRows(gridname))
{
  if (rowContainer != null)
  {
     DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);

     DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
     if (cell == null)
     {
        dataGrid1.ScrollIntoView(rowContainer, dataGrid1.Columns[column]);
        cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
      }

      //start work with cell
  }
}