繁体   English   中英

在WPF中获取DataGrid中的单元格值

[英]Getting value of cell in DataGrid in WPF

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

通常,您不需要这样做。 在WPF中,datagrid意味着与数据绑定一起使用,这意味着存在与单元格具有相同值的底层集合或对象,因此您需要直接访问该集合/对象。 如果您需要访问单元格值,则可能需要重新考虑您的设计。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM