0

There is a solution on this site that deals with getting DataGrid cell values w/out using the bound collection. In that solution a reference to GetVisualChild<T> is made... Get all cells in datagrid

Apparently MS, in their infinite wisdom, has decided to deprecate GetVisualChild<T> and there is only GetVisualChild(int).

I know we are being directed to use the bound object but, sometimes, you just have to work directly with the grid data.

Does anyone have a SUCCESSFUL means of getting cell values from a DataGrid (WPF) sans bound object?

Parrish Husband
  • 3,148
  • 18
  • 40
Doug
  • 69
  • 1
  • 1
  • 11
  • The posting mechanism dropped the at the end of a couple references to GetVisualChild(OF T) – Doug Sep 20 '18 at 16:29
  • Are you trying to get data from selected cells, cells based on col/row index, or all cells? – Parrish Husband Sep 20 '18 at 16:52
  • Hey Parrish. I was actually just trying to get ANY values from any cells for starters. Now I'll address the concept of getting the NEW values in the RowEditEnding() if possible. I may as yet break down and implement the actual Observable template. :) – Doug Sep 20 '18 at 19:54

1 Answers1

2

The problem you have, is that if the DataGrid is not bound, then you are relying on the cell content to find the value, but if some values are in checkboxes, and some are in textblocks, then you have no simple way of doing this.

What you could do is use the DataGrid's ItemContainerGenerator to get the rows, and then iterate over the row cells to try and extract values.

Perhaps your code would look something like this:

foreach (var item in grid.Items)
{
    var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
    if (row == null)
        continue;
    foreach (var column in grid.Columns)
    {
        if (!(column.GetCellContent(row) is TextBlock))
            continue;
        var cell = column.GetCellContent(row) as TextBlock;
        var text = cell?.Text; // this is the cell value
    }
}
Dean Chalk
  • 20,076
  • 6
  • 59
  • 90
  • Actually the datagrid is bound but I have not wired up the RaisePropertyChanged event because I "borrowed" from another project that uses ObservableCollection but no property events. – Doug Sep 20 '18 at 19:47
  • 1
    WOW, Dean! This actually works! You have no idea, or maybe you do, how many "solutions" for this that are out there in the wild that have obviously not been tested by the author and do not work – Doug Sep 20 '18 at 19:52
  • Im glad it works. However, personally, in reply to your first comment I would take the ObservableCollection and create a new ObservableCollection of a new ViewModel class (that implements INotifyPropertyChanged) and that ViewModel class would wrap the original objects in the original collection. Bind to the 'better' collection, then when done copy the viewmdel changes back down to the original class instances. But hey - what works, works - right :) – Dean Chalk Sep 21 '18 at 05:51