views:

843

answers:

2

I have a DataGrid whose ItemsSource is bound to a changing Observable Collection. Inside of this collection is a Business Object. Based on some of the values of the Business Object's properties, I would like to be able to modify the color of the text for each item displayed in my DataGrid once the ItemsSource is created.

Has anyone done this before or ran across something similar? Thanks in advance.

<DataTemplate x:Key="MyTemplate">
        <Grid x:Name="LayoutRoot">
            <TextBlock Text="{Binding MyText}" 
                       Foreground="{Binding MyStatus, Converter={StaticResource colorConverter}}" />
        </Grid>
    </DataTemplate>

I added the above code and inserted the TemplateColumn to the grid as below:

<data:DataGridTemplateColumn Header="Testing"
                                                 CellTemplate="{StaticResource MyTemplate}"/>

The code works fine and pulls out the correct text but the converter never fires and the Binding of the foreground is never called from the get on it.

Any ideas?

A: 

Yes. Use a Value Converter when databinding.

<UserControl.Resources>
    <myconverters:BackColor x:Key="BackColor" />
</UserControl.Resources>

<Grid x:Name="LayoutRoot" Background="{Binding SomeValue, Converter={StaticResource BackColor}" >
</Grid>

Then have your converter class implement IValueConverter and return a Brush object of some kind. You usually don't have to implement ConvertBack()

BC
I would mark this as the answer but you responded about a Grid and not a DataGrid. I have my converter setup so I'm working on that style now and will respond with a solution as well.
mstrickland
I was thinking more like the Grid would live inside the ItemTemplate.
BC
A: 

Adding to BC's answer:

You can make a DataGridTemplateColumn and specify a data template for cells in a column. In the data template you can bind the text colour.

<swcd:DataGrid ... >
    <swcd:DataGrid.Columns>
        <swcd:DataGridTemplateColumn Header="MyColumn" CellTemplate="{StaticResource MyColumnDataGridCellTemplate}"/>
         ...

in resources:

<DataTemplate x:Key="MyColumnDataGridCellTemplate">
    <Grid>
         <TextBlock Text="{Binding someproperty}" Foreground="{Binding someotherproperty, Converter={StaticResource MyConverter}}"/>
          ...
geofftnz