Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datagrid: How to get the CurrentCell of the SelectedItem?

Tags:

c#

wpf

datagrid

Within a WPF datagrid's code behind, how do I get the currentCell from my dataGrid.SelectedItem (In Code)?

Many Thanks,

like image 583
Houman Avatar asked May 12 '11 12:05

Houman


1 Answers

Try this from post

You can retrieve row from dataGrid.SelectedIndex and column by dataGrid.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;
}

Edit

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;
    }

you can find the complete source code here (look for code at end of page)

like image 190
Haris Hasan Avatar answered Sep 28 '22 01:09

Haris Hasan