Binding Foreground Property of DataGridTextColumn

Jun 26, 2009 at 3:02 PM
Edited Jun 26, 2009 at 3:15 PM

Hi all,

I need to bind the Foreground property of my DataGridTextColumn to a property of the object it is displaying (called "Colour"), in addition to binding the Text (AKA Binding) property to a different property of the same object (called "Name"). Unfortunately, I cannot seem to get this to work.

<dataGrid:DataGridTextColumn Binding="{Binding Name}" Foreground="{Binding Colour}"/> <!--Fails-->

I have a workaround, which is to use a DataGridTemplateColumn instead of a DataGridTextColumn and then add the necessary binding in the DataTemplate, however I do not understand why I cannot do this with a DataGridTextColumn (and it is somewhat combersome). Any thoughts?

<TextBlock Text="{Binding Name}" Foreground="{Binding Colour}"/>

Jun 26, 2009 at 6:03 PM

Hi Zild,

The reason the binding doesn't work on directly on the DataGridTextColumn is that we actually use two different controls within the column (one for editing mode and one for non-editing mode) to display the cell's content, so if you just set the Foreground on the column, we don't know if you want to apply that to the editing element, the non-editing element, or both.  Instead of doing the binding directly on the DataGridTextColumn, you'll want to do it in the DataGridTextColumn.ElementStyle and/or DataGridTextColumn.EditingElementStyle.  ElementStyle gives you access to Style of the control (TextBlock) which displays the cell value when not in edit mode and EditingElementStyle gives you access to the Style of the control (TextBox) which displays the cell value when in edit mode.  You can use these just like you would any other Style, by using a Setter with Property="Foregound", Value="{Binding Colour}".


Jun 29, 2009 at 8:36 AM

Thanks, Samantha, that worked a treat!

Oct 22, 2009 at 11:38 AM

Thanks Zild and Samantha. Your post helped me a lot.

For those who are stuck in writing Styles here it is:


                <Custom:DataGridTextColumn  Binding="{Binding error}" Width="0.3*" >
                        <Style TargetType="TextBlock" >
                            <Setter Property="Foreground" Value="{Binding ForegroundErrorColor}"/>