2

I know that this WPF cell background issue has been covered many times, but all the solutions I've seen use xaml (see: Change DataGrid cell colour based on values)

You may think, why no xaml? Xaml is nice if you have static colouring rules, which I do not. (My app is an electrical solver which will highlight values over and under certain security limits defined by the grid operator)

Well, I cannot have static rules to colour the cells (something like if input>0.5 return red) because the rules of colouring are defined by the user at run time.

Is there any way of achieving cell styling without using any xaml?

Right now what I use is the windows forms datagrid embeeded in a windows forms host in a WPF UI (Ugly, but works) I would really like to have the WPF data grid since its performance is much better.

Any help is appreciated.

Community
  • 1
  • 1
Santi Peñate-Vera
  • 1,053
  • 4
  • 33
  • 68
  • Have you tried anything so far? – Rohit Vats Feb 08 '14 at 19:08
  • Yes, I have done the "static" colouring setting suggested in the link which is basically the same as what is suggested here:http://social.msdn.microsoft.com/Forums/vstudio/en-US/28b6750b-d715-474f-b5b8-a2c6653ea6ca/how-to-assign-color-to-wpf-datagrid-cell-dynamically?forum=wpf, all that is nice but useless to me – Santi Peñate-Vera Feb 08 '14 at 19:12
  • `Converter` is exactly a way to do that. Are you facing any issues in that? – Rohit Vats Feb 08 '14 at 19:17
  • In fact, what makes the proposed solutions unusable in my case is that the class that defines the rule (the converter), has to be added as a resource in design time, and set as the colouring rule in design time as well, both actions programmed in xaml, perhaps I don't understand how to adapt that solution – Santi Peñate-Vera Feb 08 '14 at 19:17
  • 1
    I should write one of my `Forget winforms` type of answers. But I'm too busy right now, and I have to leave in 15 minutes. If you wait til tonight I'll write a proper answer that does not involve needless procedural code stuff, and is based on proper WPF practices and concepts such as `DataBinding` and `DataTriggers` and whatnot. – Federico Berasategui Feb 08 '14 at 19:33
  • @HighCore: I take your word ;) – Santi Peñate-Vera Feb 08 '14 at 19:35

1 Answers1

0

It is still proper databinding scenario and I see no reason to evaluate anything in your view's codebehind code. The key is to split colour calculation and it's visual representation.

  1. Encapsulate your color switching logic in row's ViewModel property with proper notification changes when colour should change.
  2. Create a converter which takes your ViewModel property type ie. string and created a Brush out of it
  3. Bind cell content's Background property to row's property using converter created in 2.
grzegorz_p
  • 483
  • 1
  • 4
  • 14