C# 当SelectionUnit=cell时,如何获取所选DataGrid单元格的内容
我想获得用户正在选择的单元格的值,如下所示: 然而,事实证明这比我想象的更具挑战性 我一直在挖掘这些内容:C# 当SelectionUnit=cell时,如何获取所选DataGrid单元格的内容,c#,wpf,datagrid,wpfdatagrid,datagridcell,C#,Wpf,Datagrid,Wpfdatagrid,Datagridcell,我想获得用户正在选择的单元格的值,如下所示: 然而,事实证明这比我想象的更具挑战性 我一直在挖掘这些内容: DataGridCellInfo currentCell = MyDataGrid.CurrentCell; DataGridCellInfo selectedCell = MyDataGrid.SelectedCells[0]; // object selectedItems = MyDataGrid.SelectedItems[0]; throws index out of ran
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();
}
有什么想法吗?我实现了这一点,但我需要将每个列的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();
}