When data is bound to a grid, how can I change the color of a label, programmatically, when a value is negative?
Hello PMac,
Allow me to start by saying that I would highly recommend against setting the colors of the cell presenters and record presenters programmatically, as you will almost certainly run into issues with the virtualization of the XamDataGrid. With that said, you can still set it by using the CellValuePresenter.FromCell method on the cell that owns the value that has changed, but again, if the virtualization of the grid is on, you will run into odd styling issues with this because the CellValuePresenter elements are recycled and reused.
Instead, I would recommend that you write a Style for CellValuePresenter to handle this. The data context of the CellValuePresenter is the underlying DataRecord to which it belongs, which has a DataItem property to return your underlying data item. So, if you bind a DataTrigger to DataItem.<propertyName>, you can then use a converter to check if your value is null and return a value to the DataTrigger that designates this. Then, in the DataTrigger, you can set the Foreground-related properties of your CellValuePresenter to the desired "negative-value" color.
Note, if you leave this Style implicit, it will affect each and every cell in your grid and so the cells for an entire row will have that foreground. If you only wish to have it effect certain Fields, I would recommend giving your Style an x:Key and applying it to your Fields' CellValuePresenterStyle properties using a StaticResource binding.
I have attached a sample project to demonstrate the above. I hope this helps you.
Please let me know if you have any other questions or concerns on this matter.
Sincerely,AndrewAssociate Developer
Thank you for your help. I am using Autotgenerated="False", hence why I was thinking of doing this programmatically.
I'll attempt the Style approach.... although I'm on V14.1 and do not see CellValuePresenterStyle attribute available for Field tags.