[英]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: 我想获取用户选择的单元格的值,如下所示:
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"?
有谁知道从哪里获得“ MEH”值? Preferably from a
DataGridCellInfo
type. 最好来自
DataGridCellInfo
类型。
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. 我设法使它适用于
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();
}
Any ideas? 有任何想法吗?
I got this to work, but I needed to specify the SortMemberPath of each column to be the property of MyRowClass
. 我得到这个工作,但我需要指定每个列的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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.