views:

116

answers:

1

Hi,

I'm trying to control the DataGrid cell background in a column conditionally on its value. Unfortunately I'm getting something like this:

alt text

Which is not very aesthetic, I would like to have the whole cell in a different colour, not only the part behind the text. Here is the code part:

<DataGridTextColumn
    Binding="{Binding Path=PrivateMemorySize, StringFormat='#,##0'}" 
    Header="Memory Size" >
    <DataGridTextColumn.ElementStyle>
        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="HorizontalAlignment" Value="Right" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=PrivateMemorySize,
                            Converter={StaticResource isLarge}, 
                            ConverterParameter=20000000}" Value="true">
                    <Setter Property="Background" Value="Yellow" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGridTextColumn.ElementStyle>
</DataGridTextColumn>

(isLarge is just a converter that returns true when the cell value is greater than the parameter)

If I define a style for the DataGridCell target, the result is the same.

Any idea on what could be wrong? I'm not using anything fancy, just the default DataGrid (which is linked in this example to CLR objects to fill in the table).

+1  A: 

In the style for your TextBlock, set the HorizontalAlignment to Stretch, and Set the TextAignment to Right:

    <Style TargetType="{x:Type TextBlock}"> 
        <Setter Property="HorizontalAlignment" Value="Stretch" />
        <Setter Property="TextAlignment" Value="Right" /> 
        <Style.Triggers> 
            <DataTrigger Binding="{Binding Path=PrivateMemorySize, 
                        Converter={StaticResource isLarge},  
                        ConverterParameter=20000000}" Value="true"> 
                <Setter Property="Background" Value="Yellow" /> 
            </DataTrigger> 
        </Style.Triggers> 
    </Style>
Scott
OK, from your answer now I understand why it didn't work. I still had to add `<Setter Property="Margin" Value="-1" />` to suppress a border and it worked perfectly, thanks!
RedGlyph
Glad I could help!
Scott