以编程方式在WPF中编辑DataGrid单元格 [英] Programmatically edit a datagrid cell in wpf

查看:406
本文介绍了以编程方式在WPF中编辑DataGrid单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要编辑单元格而不是其值,而是其背景色。我知道rowIndex和columnIndex。但是,穿越网格是很难的。我只想要类似

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

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

甚至循环在VisualTreeHelper的帮助下将起作用,但请通过它指导我。

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

谢谢

推荐答案

使用以下方法:

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的扩展方法

You can also make it as extension method on DataGrid

这篇关于以编程方式在WPF中编辑DataGrid单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆