获取单元格的值在数据网格在WPF [英] Getting value of cell in DataGrid in WPF

查看:110
本文介绍了获取单元格的值在数据网格在WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关的WinForms它的:

For WinForms it's:

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

有没有办法得到它在WPF?

Is there any way to get it in WPF?

推荐答案

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

I think the best way would be to use the Items property and directly access your data item:

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



但你可以使用这个类来获取细胞并用的GetValue()方法访问值( 。会更喜欢你的榜样)

But You can use this class to get the cell and access the value with the GetValue() method (would be more like your example).

从这里取代码:的 DataGrid中得到细胞指数

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆