I have got a WPF datagrid and I want diffrent cell colours according to values. I have got below code on my xaml
Style TargetType="DataGridCell"
but instead of selecting a cell only is selecting all row? What am I missing?
I have got a WPF datagrid and I want diffrent cell colours according to values. I have got below code on my xaml
Style TargetType="DataGridCell"
but instead of selecting a cell only is selecting all row? What am I missing?
This may be of help to you. It isn't the stock WPF datagrid however.
I used DevExpress with a custom ColorFormatter behaviour. I couldn't find anything on the market that did this out of the box. This took me a few days to develop. My code attaached below, hopefully this helps someone out there.
Edit: I used POCO view models and MVVM however you could change this to not use POCO if you desire.
Viewmodel.cs
IView.cs
View.xaml.cs
DynamicConditionBehavior.cs
View.xaml
If you try to set the
DataGrid.CellStyle
the DataContext will be the row, so if you want to change the colour based on one cell it might be easiest to do so in specific columns, especially since columns can have varying contents, like TextBlocks, ComboBoxes and CheckBoxes. Here is an example of setting all the cells light-green where theName
isJohn
:You could also use a
ValueConverter
to change the colour.Usage:
Yet another option is to directly bind the
Background
to a property which returns the respectively coloured brush. You will have to fire property change notifications in the setters of properties on which the colour is dependent.e.g.
Just put instead
But beware that this will target ALL your cells (you're aiming at all the objects of type
DataGridCell
) If you want to put a style according to the cell type, I'd recommend you to use aDataTemplateSelector
A good example can be found in Christian Mosers' DataGrid tutorial:
http://www.wpftutorial.net/DataGrid.html#rowDetails
Have fun :)
If you need to do it with a set number of columns, H.B.'s way is best. But if you don't know how many columns you are dealing with until runtime, then the below code [read: hack] will work. I am not sure if there is a better solution with an unknown number of columns. It took me two days working at it off and on to get it, so I'm sticking with it regardless.
C#
XAML
In my case convertor must return string value. I don't why, but it works.
*.xaml (common style file, which is included in another xaml files)
*.cs