c# wpf中datagrid中指定单元格背景色设置问题?

 如图所示,在子窗口中动态生成了一个比赛对阵表,想把“*”号位置处的背景设置成黑色,试了几种方法:

1。用列值绑定转换器的好像很麻烦,一是列表头是运动员的名字是不确定的,二是要设置背景色的位置也不同。不好用绑定属性的方式来改变背景色

2。根据datagrid的items来循环设置

...... for (int l=0;l< doc.dataGrid4.Items.Count;l++)

{

DataGridCell cell = GetCell(doc.dataGrid4, l+1, l+1);

cell.Background = new SolidColorBrush(Colors.Black);

}

......

public DataGridCell GetCell(DataGrid dg, int rowIndex, int columnIndex)

{

DataGridRow row = dg.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;

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;

提示出错!初学wpf求老司机带带! }

 

要实现效果如上图所示!

这种? CellTemplate 重写加载完成事件判断值 修改下背景色就好了

提供你一个思路,每次加载数据前 后台重新添加column模板,对应字段逐个加入DataGrid里,然后绑定对应数据源,其实就是把前台模板实现变为后端实现 像这样