Frage

I am using datagrid with 32 rows and when I try to use this GetCell(28,2) its fail, and also on row 28 - 32 there is the same problem.

this one: visualtreehelper.getchildrencount return 0 when its above row 28.

I find out that if i roll down to those hidden rows on the datagrid I can get those rows with GetCell() and its work fine.

how i can do that without roll down?

    public DataGridCell GetCell(int row, int column)
    {
        DataGridRow rowContainer = GetRow(row);

        if (rowContainer != null)
        {
            DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);

            DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column); 
            if (cell == null)
            {
                datagrid_arinc_const.ScrollIntoView(rowContainer, datagrid_arinc_const.Columns[column]);
                cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            }
            return cell;
        }
        return null;
    }

    public DataGridRow GetRow(int index)
    {
        DataGridRow row = (DataGridRow)datagrid_arinc_const.ItemContainerGenerator.ContainerFromIndex(index);
        if (row == null)
        {
            datagrid_arinc_const.UpdateLayout();
            datagrid_arinc_const.ScrollIntoView(datagrid_arinc_const.Items[index]);
            row = (DataGridRow)datagrid_arinc_const.ItemContainerGenerator.ContainerFromIndex(index);
        }
        return row;
    }

    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)
            {
                break;
            }
        }
        return child;
    }
War es hilfreich?

Lösung

By default UI virtualization is On for Datagrid which means only visible containers are generated.

In case you want to get dataGridRow or cell which is not visible you have to scroll down to that row manually from code behind so that its container gets generated. Refer this article here to manually scroll dataGridRow into view.

OR

Disable UI virtualization Off on dataGrid (in case don't want to scroll down) by setting VirtualizingStackPanel.IsVirtualising to false on your datagrid.

<DataGrid VirtualizingStackPanel.IsVirtualizing="False"/>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top