janderson
janderson

Reputation: 973

Make datagrid selected row text colour transparent?

Each row in our data grid application can have various background and foreground (text) colours.

The colors are added according to a property on the bound object called ForeColorFlag or BackColorFlag in the OnLoadingRow event according to a Dictionary using the following (similar for BackColorFlag):

foreach (var kvp in _foreColorFlags)
{
    var trigger = new DataTrigger {Binding = new Binding("ForeColorFlag"), Value = kvp.Key};
    var setter = new Setter(ForegroundProperty, kvp.Value);
    trigger.Setters.Add(setter);
    rowStyle.Triggers.Add(trigger);
}

For this reason it was necessary to hide which row was selected using the following:

// Remove selection style from DGV (make transparent instead of blue)
rowStyle.Resources[SystemColors.HighlightBrushKey] = Brushes.Transparent;
rowStyle.Resources[SystemColors.ControlBrushKey] = Brushes.Transparent;
rowStyle.Resources[SystemColors.HighlightTextBrushKey] = Brushes.LightGray;
rowStyle.Resources[SystemColors.ControlTextBrushKey] = Brushes.LightGray;

// stop backcolor going grey when window doesn't have focus.
rowStyle.Resources[SystemColors.InactiveSelectionHighlightBrushKey] = Brushes.Transparent;
rowStyle.Resources[SystemColors.InactiveSelectionHighlightTextBrushKey] = Brushes.LightGray;

This means that when a row is selected its background colour is what it would be if it wasn't selected. But, unfortunately the text colour (forecolor) is forced to be LightGray, setting it to Brushes.Transparent makes the text unreadable.

Is there a way to set the selected text colour (forecolor) dynamically (based on a bound property)?

Or is there a better way to do this? Is it possible to have a MultiTrigger with a PropertyTrigger (like on IsSelected) and a DataTrigger (on our ForeColorFlag)?

Thanks for your help.

Upvotes: 2

Views: 2335

Answers (2)

Ian
Ian

Reputation: 861

Add the following style to your application resource, or the resources of your DataGrid:

    <Style TargetType="{x:Type DataGridCell}" BasedOn="{StaticResource {x:Type DataGridCell}}">
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource Self}, Path=Foreground}" />
            </Trigger>
        </Style.Triggers>
    </Style>

You are telling it to set the foreground color to the color it already was, which I guess is awesome.

Upvotes: 2

Amol Bavannavar
Amol Bavannavar

Reputation: 2062

Add this style inside resources of your application or wherever it is necessary:

 <Style TargetType="{x:Type DataGridCell}">
      <Style.Triggers>
          <Trigger Property="DataGridCell.IsSelected" Value="True">
              <Setter Property="Background" Value="Transparent" />
          </Trigger>
      </Style.Triggers>
  </Style>

Upvotes: 0

Related Questions