我想获取用户选择的单元格的值,如下所示:
然而,事实证明它比我想象的更具挑战性。
我一直在挖掘这些内容:
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();
}
有任何想法吗?