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

标签 c# wpf datagrid

<分区>

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

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

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

//假设网格绑定(bind)到一些信息类的可观察集合

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

关于c# - 迭代到 WPF Datagrid 中的所有单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13449016/

相关文章:

c# - Linq 上下文对象未注册为 System.IDisposable 对象的类型

c# - 是否可以在 .NET 应用程序中运行 python?

wpf - 相对源与元素名称

wpf - 在 C# 中获取对我的 WPF ListBox 的 ScrollViewer 的引用?

WPF Datagrid 时间字段格式 hh :mm

c# - 确定单选按钮组的检查状态是否已更改

c# - "Doesn' 尝试连接到域时没有访问域所需的权限

wpf - 在 DataTemplate 中 TemplatedParent 绑定(bind)的 Silverlight RelativeSource,这可能吗?

javascript - 具有固定标题和滚动问题的 Datagrid 滚动条

c# - 按下箭头键时不触发文本框 Keydown 事件