Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting from DataGridTextColumn and overriding GenerateElement

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...

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

like image 358
PhilBrown Avatar asked Nov 05 '22 12:11

PhilBrown


1 Answers

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>
like image 105
PhilBrown Avatar answered Nov 15 '22 07:11

PhilBrown