【问题标题】:WPF : Get index of clicked / selected cell on DataGridWPF:获取 DataGrid 上单击/选定单元格的索引
【发布时间】:2013-09-04 14:27:32
【问题描述】:

如何获取 DataGrid 上单击/选定单元格的索引?
我的 DataGrid 列自动生成,我不想使用任何 DataTemplate 。

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

【问题讨论】:

  • “索引”这个词是什么意思? DataGridCellDataGridCellInfo 中没有这样的属性
  • 你想用索引做什么。什么时候可以有实际价值。

标签: wpf datagrid


【解决方案1】:
DataGrid x = (DataGrid)this.FindName("myDataGrid");
var index = x.SelectedIndex;

还有其他有用的属性:

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

【讨论】:

  • 一句警告:x.SelectedIndex 可能不是当前聚焦索引,这两个可能不同。选择索引更多的是逻辑选择,而不是用户实际看到的“选择”。
  • 进一步解释 wondra 的评论... 默认情况下:首先单击设置焦点(突出显示,并且是用户认为被选中的内容);选择第二次点击集。
【解决方案2】:

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. 我有一个只有文本列的 DataGrid,还有一个数据表(从 csv 文件创建)作为 itemssource。

 For Each cell As DataGridCellInfo In dataGrid1.SelectedCells

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

【讨论】:

  • 请记住,DisplayIndex 获取单元格相对于其他单元格的显示位置,不计算隐藏列。
【解决方案3】:

我在行索引方面遇到了同样的问题,BR1COP 给出的答案是唯一对我有用的答案。我没有使用循环,因为我只需要一个单元格的索引,任何选定的单元格。所以我是这样使用的:

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

【讨论】:

    猜你喜欢
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多