如何从WPF的数据网格中获取单元格的值?

3

可能存在重复:
选择DataGrid中的DataGridCell

我在WPF中有一个包含多列和行的DataGrid。当我点击一行时,我想获取所选行的第一列。我该如何做?我可以使用LINQ吗? 谢谢


1
请查看此问题 - gliderkite
2个回答

0

你可以简单地使用这个扩展方法-

public static DataGridRow GetSelectedRow(this DataGrid grid)
{
    return (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem);
}

你可以通过现有的行和列ID(在你的情况下为0)获取DataGrid的单元格:

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

        if (presenter == null)
        {
            grid.ScrollIntoView(row, grid.Columns[column]);
            presenter = GetVisualChild<DataGridCellsPresenter>(row);
        }

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

请查看此链接以获取详细信息 - 获取WPF DataGrid行和单元格


0
var firstSelectedCellContent = this.dataGrid.Columns[0].GetCellContent(this.dataGrid.SelectedItem);
var firstSelectedCell = firstSelectedCellContent != null ? firstSelectedCellContent.Parent as DataGridCell : null;

这样你就可以获取DataGridCell的FrameworkElement内容和DataGridCell本身。

请注意,如果DataGrid具有EnableColumnVirtualization = True,则您可能会从上面的代码中获得null值。

要从数据源中获取特定DataGridCell的实际值,需要进行一些更复杂的操作。没有通用的方法来做到这一点,因为DataGridCell可以由来自支持数据源的多个值(属性)组成,所以您需要针对特定的DataGridColumn处理此问题。


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