如何从DataGridRow获取单元格

如何从DataGridRow获取单元格

本文介绍了WPF-如何从DataGridRow获取单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据绑定的DataGrid,它具有交替的行背景色。我想根据单元格包含的数据对单元格进行不同的着色。我已经尝试过该线程建议的解决方案

I have a data-bound DataGrid with alternating row background colors. I would like to color a cell differently based on the data it contains. I have tried the solution suggested by this thread

但是,

DataGridCellsPresenter presenter = GetVisualChild(row)

DataGridCellsPresenter presenter = GetVisualChild(row)

总是返回null。

我正在使用

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

但是DataGridRow的VisualTreeHelper.GetChildrenCount()始终返回0。我已经验证DataGridRow不为null,并且已经填充了数据。

But VisualTreeHelper.GetChildrenCount() of a DataGridRow always returns 0. I have verified that DataGridRow is not null and has been populated with data already. Any help is appreciated.

谢谢。

推荐答案

您要访问的单元格的行和索引,然后在代码中执行以下操作:

If you know your row and index of the cell you'd like to access, then here's how you can do it in code:

//here's usage
var cell = myDataGrid.GetCell(row, columnIndex);
if(cell != null)
    cell.Background = Brushes.Green;

DataGrid扩展名:

DataGrid Extension:

public static class DataGridExtensions
{
    public static DataGridCell GetCell(this DataGrid grid,  DataGridRow row, int columnIndex = 0)
    {
        if (row == null) return null;

        var presenter = row.FindVisualChild<DataGridCellsPresenter>();
        if (presenter == null) return null;

        var cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
        if (cell != null) return cell;

        // now try to bring into view and retreive the cell
        grid.ScrollIntoView(row, grid.Columns[columnIndex]);
        cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);

        return cell;
    }

这篇关于WPF-如何从DataGridRow获取单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 00:52