DataGrid selection and conditional formatting

Aug 22, 2010 at 1:31 PM

I have a DataGrid with conditional formating for the Background using a Converter (xaml below).
When a Cell is selected the background I set with the converter is over the blue background of the selection. So the user doesn't know if the Cell is selected or not.
How can I do to return null from the converter if the Cell is selected?
And how can I do to assure that the converter is invoked when selection change?

<DataGridTemplateColumn Header="Price">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Background="{Binding Price, Converter={StaticResource myConverter}}" Text="{Binding Price}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

 

Aug 23, 2010 at 1:09 AM

I'm using a PriorityBinding for the background, with the first binding linked to the ancestor DataGridCell, property IsSelected.
The second binding paint the background dependent on data items.
So if the cell is selected ther first binding returns a value and the second binding isn't used. If the cell is not selected the first binding returns DependencyProperty.UnsetValue and the second binding is in charge.
It seems to be working very nicely.

xaml

<DataGridTemplateColumn Header="Price">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Price}">
                <TextBlock.Background>
                    <PriorityBinding>
                        <PriorityBinding.Bindings>
                            <Binding Path="IsSelected" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGridCell}}" Converter="{StaticResource selConverter}" />
                            <Binding Path="Price" Converter="{StaticResource myConverter}" />
                        </PriorityBinding.Bindings>
                    </PriorityBinding>
                </TextBlock.Background>
            </TextBlock>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

selConverter
    public class SelConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null && value.GetType() == typeof(bool))
            {
                if (((bool)value))
                    return null; //Background of the TextBlock is transparent, the background of the selection below (blue) will be visible
                else
                    return DependencyProperty.UnsetValue;
            }
            return DependencyProperty.UnsetValue;
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }