Programmatically edit a datagrid cell in wpf

2019-08-20 23:36发布

问题:

I want to edit the cell not its value but its background color. I know the rowIndex and the columnIndex. But to travese through the grid is a hard part. I just want something like

DataGrid.Rows[0][3].BackgroundColor=WhateverIWant

Even looping with the help of VisualTreeHelper will work, but kindly guide me through it.

Thanks

回答1:

Use following method:

public static DataGridCell GetDataGridCell(DataGrid grid, int rowIndex, int colIndex)
{
            DataGridCell result = null;
            DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(rowIndex);
            if (row != null)
            {

                    DataGridCellsPresenter presenter = GetFirstVisualChild<DataGridCellsPresenter>(row);
                    result = presenter.ItemContainerGenerator.ContainerFromIndex(colIndex) as DataGridCell;

            }

            return result;
}

public static T GetFirstVisualChild<T>(DependencyObject depObj)
        {
            if (depObj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                    if (child != null && child is T)
                    {
                        return (T)child;
                    }

                    T childItem = GetFirstVisualChild(child);
                    if (childItem != null) return childItem;
                }
            }

            return null;
        }

You can also make it as extension method on DataGrid