如何通过滚动从WPF数据网格中获取所有行

本文关键字:获取 网格 数据网 滚动 何通过 WPF 数据 | 更新日期: 2023-09-27 18:16:04

我有一些代码可以将数据从DataGrid转换为CSV文件。这很好,但我需要转换所有行,而不仅仅是当前屏幕上显示的行(Itemsource(有办法获得所有行吗?

// create one file gridview.csv in writing mode using streamwriter
            StreamWriter sw = new StreamWriter("c:''gridview.csv");
            // now add the gridview header in csv file suffix with "," delimeter except last one
            for (int i = 0; i < dgProductList.Columns.Count; i++)
            {
               sw.Write(dgProductList.Columns[i].Header);
               if (i != dgProductList.Columns.Count)
               {
                  sw.Write(",");
               }
            }
            // add new line
            sw.Write(sw.NewLine);

            // iterate through all the rows within the gridview
            foreach (DataGridRow dr in Utilities.GetDataGridRows(dgProductList))
            {
               // iterate through all colums of specific row
               for (int i = 0; i < dgProductList.Columns.Count; i++)
               {
                  // write particular cell to csv file
                  DataGridCell cell = Utilities.GetCell(dgProductList,dr, i);
                  TextBlock tb = cell.Content as TextBlock;
                  sw.Write(tb.Text);
                  if (i != dgProductList.Columns.Count)
                  {
                     sw.Write(",");
                  }
               }
               // write new line
               sw.Write(sw.NewLine);
            }
            // flush from the buffers.
            sw.Flush();
            // closes the file
            sw.Close();

 public static IEnumerable<DataGridRow> GetDataGridRows(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 DataGridRow;
            if (null != row) yield return row;
         }
      }

感谢

如何通过滚动从WPF数据网格中获取所有行

很可能是一个虚拟化问题。尝试在数据网格属性上设置VirtualizingStackPanel.IsVirtualizing="False"