如何从DataGrid获取单元格?

时间:2012-04-12 14:20:38

标签: wpf datagrid .net-3.5 border datagridcell

我有一个DataGrid(.net framework 3.5,WPFToolKit)。我想改变一些细胞的边界(左或右)。一,二或三。 那么如何才能访问单个单元格?它有可能吗? 我找到了一些解决方案,但它们适用于.net 4。

1 个答案:

答案 0 :(得分:2)

你可以扩展DataGrid并添加以下内容,注意:它只是一个示例,你不需要做我正在做的一些处理:

public DataGridCell GetCell(int row, int column)
    {
        var rowContainer = GetRow(row);

        if (rowContainer != null)
        {
            var presenter = FindVisualChild<DataGridCellsPresenter>(rowContainer);
            if (presenter == null)
                return null;

            // try to get the cell but it may possibly be virtualized
            var cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            if (cell == null)
            {
                // now try to bring into view and retreive the cell
                ScrollIntoView(rowContainer, Columns[column]);
                cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            }
            return cell;
        }
        return null;
    }

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

有关FindVisualChild的定义,请查看this site