2

I have the following DataGrid:

<DataGrid AutoGenerateColumns="False" Name="dgPanelLogs"> <DataGrid.Columns> <DataGridTextColumn Header="ID" SortMemberPath="ID" x:Name="columnID" Binding="{Binding Path=ID}" IsReadOnly="True" Width="50*" SortDirection="Descending" > </DataGridTextColumn> <DataGridTextColumn Header="Time" SortMemberPath="Time" x:Name="columnTime" Binding="{Binding Path= Time, StringFormat='{}{0:dd/MM/yyyy HH:mm:ss}'}" IsReadOnly="True" Width="140*" SortDirection="Descending"> </DataGridTextColumn> <DataGridTextColumn Header="Event" SortMemberPath="Event" x:Name="columnMessage" Binding="{Binding Path=Message}" IsReadOnly="True" Width="350*" SortDirection="Descending" > </DataGridTextColumn> </DataGrid.Columns> </DataGrid> 

My new requirement is to change rows to red when a certain value is encountered. Specifically, I have to retrieve a new boolean value with each row's data, and if it's true I need to set that row's text to red.

What's the best way to do this?

5
  • Just for clarification, you want to set the whole row to e.g. Red. Commented Apr 8, 2013 at 8:59
  • 1
    Yes, specifically the text of the row, so the foreground of each cell really. Commented Apr 8, 2013 at 9:00
  • It certainly isn't the same way you would in WinForms i.e. loop through the rows colouring the background of the cells. I wrote code to do this and it is awful - it works but it is nasty. I will share if you think you could use the code, but the correct way will be to use data binding/Triggers/Commands etc. Commented Apr 8, 2013 at 9:02
  • See my question on this exact thing as well... stackoverflow.com/questions/15657348/… Commented Apr 8, 2013 at 9:04
  • You should investigate the use of DataTriggers and Styles Commented Apr 8, 2013 at 9:05

2 Answers 2

1

The best way is to use a style.

<DataGrid.Resources> <Style TargetType="{x:Type DataGridRow}"> <Style.Triggers> <DataTrigger Binding="{Binding Alarm}" Value="True"> <Setter Property="Foreground" Value="Red" /> </DataTrigger> </Style.Triggers> </Style> </DataGrid.Resources> 

I cant test it now. I think you have to set a RelativeSource on the Binding.

Sign up to request clarification or add additional context in comments.

1 Comment

I've modified this answer. Your code was almost correct, so I fixed a typo and nested the <Style code in the context that worked.
1

I think the following posts will help you.

link1 : StackOverflow problem and answer

link2 : Styling and Templating

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.