加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:15:38 所属栏目:百科 来源:网络整理
导读:对于WinForms,它是: var value = DataGridView.Rows[0].Cells[0].Value 有没有办法在WPF中获取它? 解决方法 我认为最好的方法是使用Items属性并直接访问您的数据项: var dataItem = dataGrid.Items[0] as ...; 但是您可以使用此类来获取单元格并使用GetVa
对于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;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读