![](/img/trans.png)
[英]How to get selection of DataGrid SelectionMode=“Extended” SelectionUnit=“Cell” Binded to DataTable
[英]How to get content of selected DataGrid cell when 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();
}
有任何想法嗎?
我得到這個工作,但我需要指定每個列的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.