Программно отредактируйте ячейку сетки данных в wpf

Я хочу изменить ячейку не ее значение, а цвет фона. Я знаю rowIndex и columnIndex. Но пройти через сетку — сложная часть. Я просто хочу что-то вроде

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

Даже зацикливание с помощью VisualTreeHelper будет работать, но, пожалуйста, проведите меня через него.

Спасибо


person manav inder    schedule 16.11.2011    source источник


Ответы (1)


Используйте следующий метод:

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

Вы также можете сделать это как метод расширения в DataGrid.

person Amit    schedule 16.11.2011