[英]Programmatically edit a datagrid cell in wpf
我想編輯單元格而不是它的值,而是它的背景色。 我知道rowIndex和columnIndex。 但是,穿越網格是很難的。 我只想要像
DataGrid.Rows [0] [3] .BackgroundColor =無論如何
即使在VisualTreeHelper的幫助下進行循環也可以,但是請通過它指導我。
謝謝
使用以下方法:
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的擴展方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.