如何使用给定(row,col)索引获取DataGrid单元格的PointFromScreen

时间:2018-04-07 17:23:33

标签: wpf datagrid screen cell point

我希望使用给定(row,col)索引获取DataGrid单元格的Point From Screen。 像这样:

DataGridCellInfo firstCellInfo = Dgv.SelectedCells.First();
Point topLeft = Dgv.PointFromScreen(firstcell.PointToScreen(new Point(0, 0)));

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

添加辅助方法

    private T GetChildOfType<T>( DependencyObject depObj)
                    where T : DependencyObject
    {
        if (depObj == null) return null;

        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            var child = VisualTreeHelper.GetChild(depObj, i);

            var result = (child as T) ?? GetChildOfType<T>(child);
            if (result != null) return result;
        }
        return null;
    }

获取单元格

    private DataGridCell GetCell(DataGrid dataGrid, int row, int column)
    {
        DataGridRow rowContainer = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(row);
        if (rowContainer != null)
        {
            DataGridCellsPresenter presenter = GetChildOfType<DataGridCellsPresenter>(rowContainer);
            DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            if (cell == null)
            {
                dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[column]);
                cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            }
            return cell;
        }
        return null;
    }

用法:

        var cell = GetCell(dg, 1, 1);
        Point loc = cell.TranslatePoint(new Point(0, 0), this);
        Point PointFromScreen = cell.PointToScreen(loc);