Thursday, November 28, 2013

Change property in one datagrid column based on a value in another

This entry references WPF 4.0

This is the problem that drove me to create this blog. I wanted to change the foreground property of the document number in a datagrid to indicate when the document contained errors. With an Ultrawebgrid in .Net I would have written a RowIntialize event handler, checked the content of a hidden HasErrors column, and changed the color of the document number cell accordingly.

I Googled the problem and found about four different answers. One of them showed how to modify the Textblock class so that the foreground property became a dependent property and could be bound blah blah. I think the author must have been on crack. The answer is easy.

The STYLE tag is not your grandfather's stylesheet. It is dynamic. Style values can be bound and they can set any property, not just dependent properties. So you can use a STYLE to effectively bind any property.

So my <DataGridTextColumn> looks like this...

<DataGridTextColumn Header="Number" Binding="{Binding Path=DocumentNumber}">
    <DataGridTextColumn.ElementStyle>
        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="Foreground" Value="{Binding Path=HasErrors, Converter={StaticResource ErrorToBrushConverter}}"/>
        </Style>
    </DataGridTextColumn.ElementStyle>
</DataGridTextColumn>

There are a couple of things to note here..

It is difficult to get to the contents of the grid now. But you don't need to because it's so easy to get to the underlying data. I don't need a hidden column called HasErrors, it's just a column in the grid's dataview.

I needed to write a converter. As SQL can't return a brush type, and that's what the foreground property is, I have to convert an integer to a brush. 

No comments:

Post a Comment