数据网格:如何获取所选项目的当前单元格?

5

在WPF数据网格的代码后台中,我怎样从我的dataGrid.SelectedItem(在代码中)获取当前单元格?

非常感谢!


DataGrid的ItemsSource是什么? - Haris Hasan
Haris,该项来源是RowViewModel。如果你想知道我在视图的代码后台在做什么,我正在尝试修复一些UI问题。 - Houman
2个回答

8

帖子中尝试以下方法:

您可以通过dataGrid.SelectedIndex检索行,通过dataGrid.CurrentColumn.DisplayIndex检索列。

public static DataGridCell GetCell(DataGrid dataGrid, int row, int column)
        {
            DataGridRow rowContainer = GetRow(dataGrid, row);
            if (rowContainer != null)
            {
                DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);

                // try to get the cell but it may possibly be virtualized
                DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
                if (cell == null)
                {
                    // now try to bring into view and retreive the cell
                    dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[column]);

                    cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
                }

                return cell;
            }

            return null;
}

编辑

public static DataGridRow GetRow(DataGrid dataGrid, int index)
    {
    DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index);
        if (row == null)
        {

            dataGrid.ScrollIntoView(dataGrid.Items[index]);
            dataGrid.UpdateLayout();

            row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index);
        }

        return row;
    }

你可以在此处找到完整的源代码(寻找页面末尾的代码):这里

Haris,这听起来非常有前途。可惜他们没有实现GetRow。DataGridRow rowContainer = GetRow(dataGrid, row); 我一开始以为可以使用datagrid.SelectedItem,但这会给我ViewModel而不是行...我错过了什么? - Houman
谢谢Harris。我也找到了这个页面。它使用扩展方法,非常类似于你的方法。我已经接近成功了。最后一个问题是我需要提取DataGridCellInfo。据我所知,DataGridCellInfo是带有额外行信息的列。你有任何想法如何检索它吗?我正在尝试以编程方式设置dataGrid.CurrentCell。 - Houman
你需要 DataGridCell 还是 DataGridCellInfo - Haris Hasan
我现在已经得到了DataGridCell,感到很高兴。但是我刚意识到我还需要DataGridCellInfo。有没有办法也获取它? - Houman
没问题,哈里斯。我找到了另一种方法。我需要以编程方式设置datagrid.CurrentCell,这可以通过获取您建议的单元格并设置Cell.focus()来轻松完成。非常感谢您的帮助。 - Houman

0
您可以在DataGrid本身中使用CurrentCell.Item属性:
DataGridCell cell = (DataGridCell)myDataGrid.CurrentCell.Item;

无法将类型为 'RowViewModel' 的对象强制转换为类型为 'System.Windows.Controls.DataGridCell' 的对象。 - Houman
移除 .Item。它指向的是你的 DataGridCell 内部的内容,而不是实际的 DataGridCell。 - Rachel
2
无法将类型“System.Windows.Controls.DataGridCellInfo”转换为“System.Windows.Controls.DataGridCell”。 - Houman

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