Datagrid:如何获取SelectedItem的CurrentCell?

时间:2011-05-12 12:33:54

标签: c# wpf datagrid

在WPF数据网格的代码背后,如何从我的dataGrid.SelectedItem获取currentCell(在代码中)?

非常感谢,

2 个答案:

答案 0 :(得分:8)

post

尝试此操作

您可以从dataGrid.SelectedIndexdataGrid.CurrentColumn.DisplayIndex

列中检索行
public static DataGridCell GetCell(DataGrid dataGrid, int row, int column)
        {
            DataGridRow rowContainer = GetRow(dataGrid, row);
            if (rowContainer != null)
            {
                DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);

                // try to get the cell but it may possibly be virtualized
                DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
                if (cell == null)
                {
                    // now try to bring into view and retreive the cell
                    dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[column]);

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

                return cell;
            }

            return null;
}

修改

public static DataGridRow GetRow(DataGrid dataGrid, int index)
    {
    DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index);
        if (row == null)
        {

            dataGrid.ScrollIntoView(dataGrid.Items[index]);
            dataGrid.UpdateLayout();

            row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index);
        }

        return row;
    }

您可以找到完整的源代码here(在页面末尾查找代码)

答案 1 :(得分:0)

您可以在DataGrid本身中使用CurrentCell.Item属性:

DataGridCell cell = (DataGridCell)myDataGrid.CurrentCell.Item;