【问题标题】:How to get PointFromScreen of a DataGrid cell using given (row, col) index如何使用给定的(行,列)索引获取 DataGrid 单元格的 PointFromScreen
【发布时间】:2018-09-17 11:56:33
【问题描述】:
我想使用给定的 (row, col) 索引从屏幕中获取 DataGrid 单元格的点。
像这样的:
DataGridCellInfo firstCellInfo = Dgv.SelectedCells.First();
Point topLeft = Dgv.PointFromScreen(firstcell.PointToScreen(new Point(0, 0)));
我怎样才能做到这一点?
【问题讨论】:
标签:
wpf
datagrid
screen
cell
point
【解决方案1】:
添加辅助方法
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);