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?

DaveDev
  • 41,155
  • 72
  • 223
  • 385
  • Just for clarification, you want to set the whole row to e.g. Red. – DHN Apr 08 '13 at 08:59
  • 1
    Yes, specifically the *text* of the row, so the foreground of each cell really. – DaveDev Apr 08 '13 at 09: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. – MoonKnight Apr 08 '13 at 09:02
  • See my question on this exact thing as well... http://stackoverflow.com/questions/15657348/looping-through-wpf-datagrid-using-foreach – MoonKnight Apr 08 '13 at 09:04
  • You should investigate the use of DataTriggers and Styles – RJ Lohan Apr 08 '13 at 09:05

2 Answers2

1

I think the following posts will help you.

link1 : StackOverflow problem and answer

link2 : Styling and Templating

Community
  • 1
  • 1
Haritha
  • 1,498
  • 1
  • 13
  • 35
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.

DaveDev
  • 41,155
  • 72
  • 223
  • 385
Andre
  • 1,044
  • 1
  • 11
  • 23