【发布时间】:2016-10-08 02:48:34
【问题描述】:
我在这里使用此代码部署。但是在 GetCell 中的转换,在该行中获取 null 并且无法更改单元格的颜色。我要做的是获取单元格,然后根据它们的值将单元格颜色更改为红色或绿色。
public void ColorChange()
{
DataGridCell cell = GetCell(11, 1, dgLectura);
cell.Background = new SolidColorBrush(Colors.Red);
}
public DataGridCell GetCell(int rowIndex, int columnIndex, DataGrid dg)
{
//DataGridRow row = dg.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;
DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(rowIndex);
if (row == null)
{
dg.UpdateLayout();
dg.ScrollIntoView(dg.Items[rowIndex]);
row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(rowIndex);
}
DataGridCellsPresenter p = GetVisualChild<DataGridCellsPresenter>(row);
DataGridCell cell = p.ItemContainerGenerator.ContainerFromIndex(columnIndex) as DataGridCell;
return cell;
}
static T GetVisualChild<T>(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}
【问题讨论】:
标签: c# wpf datagrid wpfdatagrid