WPF:获取DataGrid上点击/选择单元格的索引

7

如何获取 DataGrid 中所选单元格的索引?
我的 DataGrid 列是自动生成的,我不想使用任何 DataTemplate。

<DataGrid ItemsSource="{Binding Table, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, IsAsync=True}"
          AutoGenerateColumns="True">
</DataGrid>

你说的“index”是什么意思?在DataGridCellDataGridCellInfo中都没有这样的属性。 - WiiMaxx
当你可以拥有实际的值时,索引有什么用处。 - JSJ
3个回答

12
DataGrid x = (DataGrid)this.FindName("myDataGrid");
var index = x.SelectedIndex;

还有其他有用的属性:

x.CurrentColumn;
x.CurrentItem;
x.SelectedItem;
x.SelectedValue;

1
一个警告:x.SelectedIndex 可能是当前聚焦的索引,也可能不是。选定的索引更多地是逻辑选择,而不是用户实际上看到的“选定”。 - wondra
进一步回应wondra的评论...默认情况下:第一次单击设置焦点(高亮显示,并且是用户认为已选择的内容);第二次单击设置所选内容。 - John Doe

2

当选择单元格并需要循环遍历已选单元格以获取行和列索引时,我找到了以下解决方案。我的DataGrid只有textcolumn,并且datatable(从csv文件创建)作为itemssource。

 For Each cell As DataGridCellInfo In dataGrid1.SelectedCells

         MsgBox(cell.Column.DisplayIndex)
         MsgBox(dataGrid1.Items.IndexOf(cell.Item))
 Next

请注意,DisplayIndex获取单元格相对于其他单元格的显示位置,不包括隐藏列。 - Volkan Sen

0

我遇到了相同的问题,对于行索引的解决方案,BR1COP给出的答案是唯一起作用的。由于我只需要一个单元格的索引,而不是使用循环,所以我按照以下方式使用它:

DataGridCellInfo cell = myGrid.SelectedCells[0];
int rowIndex = dividingGrid.Items.IndexOf(cell.Item);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接