迭代到WPF Datagrid中的所有单元格 [英] Iterate to all cells in WPF Datagrid

查看:119
本文介绍了迭代到WPF Datagrid中的所有单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

WPF DataGrid:如何在DataGrid中迭代获取行和列?

我有一个 WPF DataGrid 。我想迭代 Datagrid 中的所有单元格
给我一个简单的代码来做到这一点。
像这样

I have a WPF DataGrid. I want to iterate all cells in Datagrid. Give me a simple code to do that. Like this

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


推荐答案

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

这篇关于迭代到WPF Datagrid中的所有单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆