Question

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

Was it helpful?

Solution

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top