Как получить содержимое выбранной ячейки DataGrid, когда SelectionUnit=Cell

Я хочу получить значение ячейки, которую пользователь выбирает так:

Однако это оказалось сложнее, чем я думал.

Я копался в содержании этих:

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

Но я не могу найти простой текст ни в одном из них. Кто-нибудь знает, где взять значение "MEH"? Предпочтительно из DataGridCellInfo тип.

Заранее спасибо.

Редактировать:

Мне удалось заставить это работать на DataGridTextColumnsно у меня тоже есть DataGridTemplateColumns и это нужно, чтобы работать на тех, кто тоже.

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

Есть идеи?

1 ответ

Решение

Я получил это на работу, но мне нужно было указать SortMemberPath каждого столбца, чтобы быть свойством 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();
}
Другие вопросы по тегам