WPF:获取 DataGrid 上单击/选定单元格的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18616539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF : Get index of clicked / selected cell on DataGrid
提问by Shahin
How do I get index of clicked / selected cell on DataGrid ?
My DataGrid columns generated automatically and I don't want to use any DataTemplate .
如何在 DataGrid 上获取单击/选定单元格的索引?
我的 DataGrid 列是自动生成的,我不想使用任何 DataTemplate 。
<DataGrid ItemsSource="{Binding Table, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, IsAsync=True}"
AutoGenerateColumns="True">
</DataGrid>
回答by Ivan Peric
DataGrid x = (DataGrid)this.FindName("myDataGrid");
var index = x.SelectedIndex;
There are also other usefull properties:
还有其他有用的属性:
x.CurrentColumn;
x.CurrentItem;
x.SelectedItem;
x.SelectedValue;
回答by BR1COP
This is the solution I found, when selection unit is "cell" and you need to loop through the selected cells, getting row and column index. I have a DataGrid with textcolumn only, and a datatable (creted from a csv file) as itemssource.
This is the solution I found, when selection unit is "cell" and you need to loop through the selected cells, getting row and column index. 我有一个只有 textcolumn 的 DataGrid,还有一个数据表(从 csv 文件中提取)作为项目源。
For Each cell As DataGridCellInfo In dataGrid1.SelectedCells
MsgBox(cell.Column.DisplayIndex)
MsgBox(dataGrid1.Items.IndexOf(cell.Item))
Next
回答by Tharmas
I had the same problem with the row index, and the answer given by BR1COP was the only one that worked for me. I didn't use the loop as I only needed the index of one cell, any selected cell. So I used it like this:
我在行索引方面遇到了同样的问题,BR1COP 给出的答案是唯一对我有用的答案。我没有使用循环,因为我只需要一个单元格的索引,任何选定的单元格。所以我是这样使用的:
DataGridCellInfo cell = myGrid.SelectedCells[0];
int rowIndex = dividingGrid.Items.IndexOf(cell.Item);

