1

我想要 DataGrid 的选定列的索引。例如,如果我选择第一列,我想要第一列的索引(索引 = 0)。

我在 DataGrid SelectionChanged 事件中尝试过,但我似乎无法获得特定的列索引。如果有人知道该怎么做,请帮助我提供一些示例代码。

4

2 回答 2

0

DataGrid.Items 属性返回一个表示DataGrid 中DataGridItems 的DataGridItemCollection。

每个 DataGridItem 代表呈现表中的单行。此外,DataGridItem 公开了一个代表编号的 Cells 属性。呈现的表格中的表格单元(换句话说,列)。

// Get the Row Count
int rowCount = myGrid.Items.Count;

// Get the no. of columns in the first row.
int colCount = myGrid.Items[0].Cells.Count;
于 2013-10-24T05:56:04.883 回答
0

我假设您想要选择的任何列的索引。这是我想出的代码:

    List<int> selectedColumnIndexes = new List<int>(dataGrid.SelectedCells.Count);

    for (int i = 0; i < dataGrid.SelectedCells.Count; i++)
    {
        foreach (DataGridColumn column in dataGrid.Columns)
        {
            if (column.DisplayIndex == dataGrid.SelectedCells[i].Column.DisplayIndex) 
            {
                    if (!selectedColumnIndexes.Contains(column.DisplayIndex))
                    {
                        selectedColumnIndexes.Add(column.DisplayIndex);
                    }
            }
        }
    }

因此,您将拥有当前选定列的所有索引的列表。这个问题提供了一些很好的线索,说明了这里的发展方向。

显然,如果您只想要实际选择的列数,那么在 for 循环运行之后,该值就是 selectedColumnIndexes.Count 。

于 2013-10-24T08:58:16.580 回答