【问题标题】:Iterate to all cells in WPF Datagrid [duplicate]迭代到WPF Datagrid中的所有单元格[重复]
【发布时间】:2012-11-19 06:57:41
【问题描述】:

可能重复:
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
    }
}

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:
     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
      }
    }
    

    【讨论】:

    • 如何在 foreach 循环中访问该行的每个单元格?
    • @WPFK - 如果您在 foreach 循环中使用一些对象可观察集合来请求网格,您将读取与我在回答中给出的每一行网格关联的对象,例如他的“信息信息 = (sInfo) r.Item;"
    • 但这里的问题是我想访问单元格属性、单元格的列标题等。我无法访问绑定到数据网格的对象。
    • @WPFK- 更新的答案试过了..
    • 错误:使用泛型类型 'System.Collections.Generic.IEnumerable' 需要 1 个类型参数
    猜你喜欢
    • 1970-01-01
    • 2017-04-22
    • 2011-10-08
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 2011-06-25
    • 2013-06-24
    • 1970-01-01
    相关资源
    最近更新 更多