views:

99

answers:

1

I'm attempting to create a custom DataGrid where I can format individual cells based on the cell value (ie; red text for negative values, green for postitive) ala this approach...

http://stackoverflow.com/questions/686165/how-to-get-binding-value-of-current-cell-in-a-wpftoolkit-datagrid

I also need to convert the values from negative to parenthesised (ie; -2.34 to (2.34)). I've got the inheritance/overide working. My question is, how do I get access to the values in the cells in the overridden GenerateElement method.

Thanks in advance, Phil

+1  A: 

My approach was wrong. I needed to use IValueConverter and bind the Text and Foreground properties like so...

type FixedDecimalConverter() =
    interface  IValueConverter with
        member this.Convert(value, targetType, parameter, culture) = 
            match value :?> Double with 
                | Globals.DataGridHelper.IsNegative x -> 
                    sprintf "(%.2f%%)" (Math.Abs x) :> obj                        
                | Globals.DataGridHelper.IsPositive x -> 
                    sprintf "%.2f%%" x :> obj

        member this.ConvertBack(value, targetType, parameter, culture) = raise <| NotImplementedException()

type ForegroundValueConverter() =
    interface  IValueConverter with
        member this.Convert(value, targetType, parameter, culture) = 
            match value :?> Double with 
                | Globals.DataGridHelper.IsNegative x -> Globals.DataGridHelper.redBrush :> obj
                | Globals.DataGridHelper.IsPositive x -> Globals.DataGridHelper.greenBrush :> obj

        member this.ConvertBack(value, targetType, parameter, culture) = raise <| NotImplementedException()

And the Xaml...

<data:DataGridTemplateColumn Header="YTD v. Sector" x:Name="YTDvSector" Visibility="Collapsed">
                            <data:DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <TextBlock  TextAlignment="Right" VerticalAlignment="Center"
                                            Text="{Binding ytdSectorReturn.value, Converter={StaticResource fcFixedDecimalConverter}}"
                                            Foreground="{Binding ytdSectorReturn.value, Converter={StaticResource fcForegroundValueConverter}}"/>
                                </DataTemplate>
                            </data:DataGridTemplateColumn.CellTemplate>
                        </data:DataGridTemplateColumn>

And the plumbing...

<UserControl.Resources>
        <y:FixedDecimalConverter x:Key="fcFixedDecimalConverter" />
        <y:ForegroundValueConverter x:Key="fcForegroundValueConverter" />
    </UserControl.Resources>
PhilBrown