如何获取 DataGrid 中所选单元格的索引?
我的 DataGrid 列是自动生成的,我不想使用任何 DataTemplate。
<DataGrid ItemsSource="{Binding Table, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, IsAsync=True}"
AutoGenerateColumns="True">
</DataGrid>
如何获取 DataGrid 中所选单元格的索引?
我的 DataGrid 列是自动生成的,我不想使用任何 DataTemplate。
<DataGrid ItemsSource="{Binding Table, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, IsAsync=True}"
AutoGenerateColumns="True">
</DataGrid>
DataGrid x = (DataGrid)this.FindName("myDataGrid");
var index = x.SelectedIndex;
还有其他有用的属性:
x.CurrentColumn;
x.CurrentItem;
x.SelectedItem;
x.SelectedValue;
x.SelectedIndex
可能是当前聚焦的索引,也可能不是。选定的索引更多地是逻辑选择,而不是用户实际上看到的“选定”。 - wondra当选择单元格并需要循环遍历已选单元格以获取行和列索引时,我找到了以下解决方案。我的DataGrid只有textcolumn,并且datatable(从csv文件创建)作为itemssource。
For Each cell As DataGridCellInfo In dataGrid1.SelectedCells
MsgBox(cell.Column.DisplayIndex)
MsgBox(dataGrid1.Items.IndexOf(cell.Item))
Next
我遇到了相同的问题,对于行索引的解决方案,BR1COP给出的答案是唯一起作用的。由于我只需要一个单元格的索引,而不是使用循环,所以我按照以下方式使用它:
DataGridCellInfo cell = myGrid.SelectedCells[0];
int rowIndex = dividingGrid.Items.IndexOf(cell.Item);