0

我想获取用户选择的单元格的值,如下所示:

在此处输入图像描述

然而,事实证明它比我想象的更具挑战性。

我一直在挖掘这些内容:

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

有任何想法吗?

4

1 回答 1

0

我得到了这个工作,但我需要将每列的 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();
}
于 2015-09-23T21:48:06.840 回答