迭代到 WPF Datagrid 中的所有单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13449016/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 06:16:20  来源:igfitidea点击:

Iterate to all cells in WPF Datagrid

c#wpfdatagrid

提问by Kishor

Possible Duplicate:
WPF DataGrid: How do you iterate in a DataGrid to get rows and columns?

可能的重复:
WPF DataGrid:如何在 DataGrid 中迭代以获取行和列?

I have a WPFDataGrid. I want to iterate all cellsin Datagrid. Give me a simple code to do that. Like this

我有一个WPFDataGrid. 我想cellsDatagrid. 给我一个简单的代码来做到这一点。像这样

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

采纳答案by Pranay Rana

 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;
      }
 }

//assuming that grid is bind to observable collection of some info class

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

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
  }
}