[英]Programmatically edit a datagrid cell in wpf
I want to edit the cell not its value but its background color. 我想编辑单元格而不是它的值,而是它的背景色。 I know the rowIndex and the columnIndex.
我知道rowIndex和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 =无论如何
Even looping with the help of VisualTreeHelper will work, but kindly guide me through it. 即使在VisualTreeHelper的帮助下进行循环也可以,但是请通过它指导我。
Thanks 谢谢
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 您也可以将其作为DataGrid的扩展方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.