Search code examples
c#wpfdatagridwpfdatagriddatagridcell

How to get content of selected DataGrid cell when SelectionUnit=Cell


I want to get the value of the cell the user is selecting like so:

enter image description here

However it's turning out to be more challenging than I thought it would be.

I've been digging around on the contents of these:

DataGridCellInfo currentCell = MyDataGrid.CurrentCell;
DataGridCellInfo selectedCell = MyDataGrid.SelectedCells[0];

// object selectedItems = MyDataGrid.SelectedItems[0]; throws index out of range error

object selectedValue = MyDataGrid.SelectedValue; // null
object selectedItem = MyDataGrid.SelectedItem; // null

But I can't find the simple text in any of these. Does anyone know where to get the value "MEH"? Preferably from a DataGridCellInfo type.

Thanks in advance.

Edit:

I managed to get this to work for DataGridTextColumns, but I also have DataGridTemplateColumns and need it to work for those too.

public string GetSelectedCellValue()
{
    DataGridCellInfo cellInfo = MyDataGrid.SelectedCells[0];
    if (cellInfo == null) return null;

    DataGridBoundColumn column = cellInfo.Column as DataGridBoundColumn;
    if (column == null) return null;

    FrameworkElement element = new FrameworkElement() { DataContext = cellInfo.Item };
    BindingOperations.SetBinding(element, TagProperty, column.Binding);

    return element.Tag.ToString();
}

Any ideas?


Solution

  • I got this to work, but I needed to specify the SortMemberPath of each column to be the property of MyRowClass.

    public string GetSelectedCellValue()
    {
        DataGridCellInfo cells = MyDataGrid.SelectedCells[0];
    
        YourRowClass item = cells.Item as YourRowClass;
    
        // specify the sort member path of the column to that YourRowClass property 
        string columnName = cells.Column.SortMemberPath; 
    
        if (item == null || columnName == null) return null;
    
        object result = item.GetType().GetProperty(columnName).GetValue(item, null);
    
        if (result == null) return null;
    
        return result.ToString();
    }