How to get a cell from DataGrid?

2019-02-28 05:37发布

I have a DataGrid (.net framework 3.5, WPFToolKit). And i want to change borders (left or right) of some cells. One, two or three. So how can I get an access to a single cell? And is it possible? I've found some solutions, but they are for .net 4.

1条回答
看我几分像从前
2楼-- · 2019-02-28 05:57

You can extend the DataGrid and add the following, NOTE: it's just a sample, you don't need to do some of the processing that I am doing:

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

For the definition of FindVisualChild, look at this site.

查看更多
登录 后发表回答