Getting DataGridCellsPresenter from/of a DataGridRow

Mar 24, 2009 at 6:47 PM

How can I get the DataGridCellsPresenter object from/of a DataGridRow? Please, this is an urgent query.

Thanks in advance.

Mar 24, 2009 at 8:48 PM
DataGrid doesn't expose an API to do this. It would be interesting to know your scenario for needing it.

If you have access to a cell, you can get to the DataGridCellsPresenter by calling ItemsControl.ItemsControlFromItemContainer(cell).
If you don't then you can do a tree walk down from the DataGridRow using VisualTreeHelper.GetChild and GetChildrenCount. It is relatively close to the top of the default template.
If you have replaced the template for the DataGridRow, you can set x:Name to a name on the DataGridCellsPresenter. Then call myDataGridRow.Template.FindName(theNameYouPutOnDataGridCellsPresenter, myDataGridRow).

Hope that helps,
Mar 25, 2009 at 11:59 AM

Thanks for the reply Ben. I want to get a specific cell based of the Column Number and Row Number from the datagrid. I found an thread

Which provides a way of doing this but has the following line of code:


DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);

//Where rowContainer is the row containing the DataGridCell I am after.

Which I am finding a bit difficult to understand.

Mar 25, 2009 at 3:38 PM
Edited Mar 25, 2009 at 3:45 PM
I am trying this code for but its not working properly.

private DataGridCellsPresenter GetVisualChild<T1>(DataGridRow rowContainer)
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(this.dataGrid1); i++)
                if (VisualTreeHelper.GetChild(this.dataGrid1, i).GetType().Name.Equals("DataGridCellsPresenter"))
                    return (DataGridCellsPresenter)VisualTreeHelper.GetChild(rowContainer, i);
            return null;            

This returns me a null as the VisualTreeHelper.GetChildrenCount(this.dataGrid1) always returns 1, which is Border.

Mar 25, 2009 at 7:37 PM
You will want to use this code from the thread you referred to:
public static T GetVisualChild<T>(Visual parent) where T : Visual
    T child = default(T);
    int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < numVisuals; i++)
        Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
        child = v as T;
        if (child == null)
            child = GetVisualChild<T>(v);
        if (child != null)
    return child;

Then when you want a DataGridCellsPresenter:
Mar 26, 2009 at 10:51 AM
Many thanks Ben, this worked.