我目前已设置此方法来检测DataGrid中每一行的双击:

private void Row_DoubleClick(object sender, RoutedEventArgs e)
    {
        DataGridRow row = (DataGridRow)sender;
        DataRow dr = (DataRow)row.DataContext;
        string value = dr[0].ToString();
        MessageBox.Show(value);
    }


我的问题是我似乎无法获取单元格值。如您所见,我试图获取该行中第一个单元格的值,但是它将崩溃。有什么想法可以做到吗? :)

最佳答案

尝试这个。

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;
 }

关于c# - 如何获取DataGridRow单元格值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28533905/

10-13 08:07