Tuesday, February 03, 2009

WPF DataGrid Conditional Formatting

I recently ran into a problem on my project where I needed to apply some conditional formatting to WPF DataGrid Cells based upon values from another property in my bound object.

The requirement was pretty simple: if condition is met, change the cell-text color to red, otherwise, leave it black.  What should have been a pretty simple task (never heard a programmer say that, right?) ended up taking me more time than I’d care to admit.

After fumbling around with a few attempts at the IValueConverter and a DataTemplateSelector, I still was not having any luck in getting my conditional formatting to work.  I eventually landed back at my usual source of information for the WPF ToolkitCodePlex, and “shockingly”, the answer was in the discussion for the project.

I had been fighting the “Foreground” property of the DataGridTextColumn directly, trying what was recommended in this article, but I just couldn’t get that working.  Once I followed the CodePlex forum recommendation of embedding a CellStyle into the DataGridTextColumn, things worked as expected.

1 comment:

  1. Thanks for posting. I am just starting down this road and you saved me a ton of time.