1
votes

I've got a WPF datagrid bound to a list of parts and I need alternating row colors. The parts can also be part of a group, in which case the entire group needs to be the same color. Kind of like:

Part 1, group 1  -  White background
Part 2, group 2  -  Blue background
Part 3, group 3  -  White background
Part 4, group 3  -  White background
Part 5, group 4  -  Blue background
Part 6, group 4  -  Blue background
Part 7, group 5  -  White background

The alternation of color must be based on groups, not simply by every other row. I have tried using grid.ItemContainerGenerator in the codebehind when the source collection is updated, but this does not work. ItemContainerGenerator.ContainerFromIndex() always returns null at this time, I suppose because the grid is still updating, I don't know. How can I do this?

3

3 Answers

0
votes

In complex scenarios (like color denoting status, for example), I create a property on the viewmodel that returns a Color for the BackgroundBrush based on whatever rules you want. I typically create a static instance that I return repeatedly for each group, and freeze it, to conserve resources.

HTH...

0
votes

I have used RowLoaded/RowUnloaded in the past, and using a behavior told the row what property of the rows datacontext contains the background. The problem that I have found is that binding a rows Background for some reason climbs up to the Grid's DataContext, instead of using the rows. If you are interested in this approach I can paste the code I have use. It does require that the ViewModel or ListViewModel be aware enough to set the correct colors for the rows. I have been often on the fence about colors in ViewModel, but color has become a business need and not just an ascetic effort.

0
votes

What I did was overriding the following event of the DataGrid class

protected override void PrepareContainerForItemOverride(System.Windows.DependencyObject element, object item)

After calling the base method, you can set background color of the row based on the value of the item variable, which you can convert to group class and access properties such as group name for example.