Подтвердить что ты не робот

Выберите DataGridCell из DataGrid

У меня есть элемент управления DataGrid WPF, и я хочу получить конкретный DataGridCell. Я знаю индексы строк и столбцов. Как я могу это сделать?

Мне нужен DataGridCell, потому что я должен иметь доступ к его Контенту. Поэтому, если у меня есть (например) столбец DataGridTextColum, мой контент будет объектом TextBlock.

4b9b3361

Ответ 1

Вы можете использовать код, подобный этому, для выбора ячейки:

var dataGridCellInfo = new DataGridCellInfo(
    dataGrid.Items[rowNo], dataGrid.Columns[colNo]);

dataGrid.SelectedCells.Clear();
dataGrid.SelectedCells.Add(dataGridCellInfo);
dataGrid.CurrentCell = dataGridCellInfo;

Я не вижу способ напрямую обновить содержимое конкретной ячейки, поэтому, чтобы обновить содержимое конкретной ячейки, я сделаю следующее

// gets the data item bound to the row that contains the current cell
// and casts to your data type.
var item = dataGrid.CurrentItem as MyDataItem;

if(item != null){
    // update the property on your item associated with column 'n'
    item.MyProperty = "new value";
}
// assuming your data item implements INotifyPropertyChanged the cell will be updated.

Ответ 2

Вы можете просто использовать этот метод расширения -

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

и вы можете получить ячейку DataGrid существующим идентификатором строки и столбца:

public static DataGridCell GetCell(this DataGrid grid, DataGridRow row, int column)
{
    if (row != null)
    {
        DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);

        if (presenter == null)
        {
            grid.ScrollIntoView(row, grid.Columns[column]);
            presenter = GetVisualChild<DataGridCellsPresenter>(row);
        }

        DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
        return cell;
    }
    return null;
}

grid.ScrollIntoView - это ключ к выполнению этой работы в случае, если DataGrid виртуализирован и требуемая ячейка не отображается в настоящее время.

Подробнее см. эту ссылку - Получить строку и ячейку WPF DataGrid

Ответ 3

Вот код, который я использовал:

    /// <summary>
    /// Get the cell of the datagrid.
    /// </summary>
    /// <param name="dataGrid">The data grid in question</param>
    /// <param name="cellInfo">The cell information for a row of that datagrid</param>
    /// <param name="cellIndex">The row index of the cell to find. </param>
    /// <returns>The cell or null</returns>
    private DataGridCell TryToFindGridCell(DataGrid dataGrid, DataGridCellInfo cellInfo, int cellIndex = -1)
    {
        DataGridRow row;
        DataGridCell result = null;

        if (dataGrid != null && cellInfo != null)
        {
            if (cellIndex < 0)
            {
                row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromItem(cellInfo.Item);
            }
            else
            {
                row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(cellIndex);
            }

            if (row != null)
            {
                int columnIndex = dataGrid.Columns.IndexOf(cellInfo.Column);

                if (columnIndex > -1)
                {
                    DataGridCellsPresenter presenter = this.FindVisualChild<DataGridCellsPresenter>(row);

                    if (presenter != null)
                    {
                        result = presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex) as DataGridCell;
                    }
                    else
                    {
                        result = null;
                    }
                }
            }
        }

        return result;
    }`

Это предполагает, что DataGrid уже загружен (выполняется собственный обработчик Loaded).