Select DataGridCell from DataGrid

后端 未结 3 1658
逝去的感伤
逝去的感伤 2020-12-17 17:30

I have a DataGrid WPF control and I want to get a specific DataGridCell. I know the row and column indices. How can I do this?

I need the

3条回答
  •  渐次进展
    2020-12-17 18:04

    You can simply use this extension method-

    public static DataGridRow GetSelectedRow(this DataGrid grid)
    {
        return (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem);
    }
    

    and you can get a cell of a DataGrid by an existing row and column id:

    public static DataGridCell GetCell(this DataGrid grid, DataGridRow row, int column)
    {
        if (row != null)
        {
            DataGridCellsPresenter presenter = GetVisualChild(row);
    
            if (presenter == null)
            {
                grid.ScrollIntoView(row, grid.Columns[column]);
                presenter = GetVisualChild(row);
            }
    
            DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            return cell;
        }
        return null;
    }
    

    grid.ScrollIntoView is the key to make this work in case DataGrid is virtualized and required cell is not in view currently.

    Check this link for details - Get WPF DataGrid row and cell

提交回复
热议问题