c# - 在 WPF 中获取 DataGrid 中单元格的值

标签 c# wpf datagrid

对于 WinForms,它是:

var value = DataGridView.Rows[0].Cells[0].Value

有什么方法可以在 WPF 中获取它吗?

最佳答案

我认为最好的方法是使用 Items 属性并直接访问您的数据项:

var dataItem = dataGrid.Items[0] as ...;

但是您可以使用此类获取单元格并使用 GetValue() 方法访问值(更像您的示例)。

代码取自此处:datagrid get cell index

static class DataGridHelper {
    static public DataGridCell GetCell(DataGrid dg, int row, int column) {
        DataGridRow rowContainer = GetRow(dg, 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
                dg.ScrollIntoView(rowContainer, dg.Columns[column]);
                cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            }
            return cell;
        }
        return null;
    }

    static public DataGridRow GetRow(DataGrid dg, int index) {
        DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
        if (row == null) {
            // may be virtualized, bring into view and try again
            dg.ScrollIntoView(dg.Items[index]);
            row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
        }
        return row;
    }

    static T GetVisualChild<T>(Visual parent) where T : Visual {
        T child = default(T);
        int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < numVisuals; i++) {
            Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
            child = v as T;
            if (child == null) {
                child = GetVisualChild<T>(v);
            }
            if (child != null) {
                break;
            }
        }
        return child;
    }
}

关于c# - 在 WPF 中获取 DataGrid 中单元格的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13204536/

相关文章:

c# - WPF 应用程序中的全屏

wpf - VS 2012 扩展中的标准控件

c# - 有没有办法获得 "kill"模型属性?

c# - 多线程环境下 SendOrPostCallback 和 Action 的区别?

C# 与 MySQL 连接器 - 访问被拒绝

c# - 使用 MEF 时 Type.GetType 返回 null

单击行时未引发 Silverlight DataGrid MouseLeftButtonDown 事件

c# - 无法对 DataGrid 中的日期列进行排序

C# Selenium 使用不同的用户配置文件启动 Chrome

c# - 在 Excel C# 中的特定单元格中插入文本