简体   繁体   中英

Change WPF DataGrid cell background programatically (without using XAML)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM