所有,我试图循环通过
WPF DataGrid使用for each循环来改变错误单元格的背景颜色.我检查了很多问题,但我还没有找到足够的答案.到目前为止我所拥有的是什么
- public void RunChecks()
- {
- const int baseColumnCount = 3;
- foreach (DataRowView rv in dataGrid.Items)
- {
- for (int i = baseColumnCount; i < dataGrid.Columns.Count; i++)
- {
- if (!CheckForBalancedParentheses(rv.Row[i].ToString()))
- {
- Color color = (Color)ColorConverter.ConvertFromString("#FF0000");
- row.Background = new SolidColorBrush(color); // Problem!
- }
- }
- }
- }
问题是,为了更改DataGrid中行的背景颜色,我需要使用与DataRowView rv相关的DataGridRow对象.
如何从对象rv(DataRowView)获取对DataGridRow的引用?
谢谢你的时间.
编辑.基于下面的建议,我现在有以下样式,它与鼠标悬停在事件上并设置相关单元格的后退和前导字体.但是,我真的迷失了如何在上面的代码中在运行时将backcolor应用到单元格. XML风格是
- <Window.Resources>
- <Style TargetType="{x:Type DataGridRow}">
- <Style.Triggers>
- <Trigger Property="IsMouSEOver"
- Value="True">
- <Setter Property="Background" Value="Red" />
- <Setter Property="FontWeight" Value="ExtraBold" />
- </Trigger>
- </Style.Triggers>
- </Style>
- </Window.Resources>
解决方法
在使用WPF时,请避免始终直接访问UI工件.
在ModelView中创建属性Color,并将其绑定到DataGrid视图的单行模板的背景颜色.
因此,为了更改颜色,您将循环抛出ModelView collecton并设置/读取绑定到每一行的每个对象的Color属性.通过更改它,如果正确设置了绑定,则会影响行UI颜色外观.
对于具体样品,您可以查看:
How do I bind the background of a data grid row to specific color?