Family
Family

Reputation: 1113

Change entire row colour, not just cell

I have the following code in xaml:

<DataGrid Name="DgAlarmsGrid" AutoGenerateColumns="True" Grid.Row="1"
          HorizontalAlignment="Stretch" Margin="5,29,5,10"  
          VerticalAlignment="Stretch" RenderTransformOrigin="0.517,0.861" Grid.RowSpan="2" ItemsSource="{Binding Items}">
  <DataGrid.Resources>
    <pagingDemo:ValueColorConverter x:Key="Colorconverter"/>
  </DataGrid.Resources>
  <DataGrid.CellStyle>
    <Style TargetType="DataGridCell">
      <Style.Triggers>
        <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Column.DisplayIndex}" Value="10">
          <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Path=Content.Text, Converter={StaticResource Colorconverter}}"/>
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </DataGrid.CellStyle>
</DataGrid>

And this class:

public class ValueColorConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    var str = value as string;
    if (str == null) return null;
    int intValue;
    if (!int.TryParse(str, out intValue)) return null;
    if (intValue < 0) return (MainWindow.AlarmColours[256]);
    return (intValue > 255) ? null : (MainWindow.AlarmColours[intValue]);
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    throw new NotImplementedException();
  }
}

This colours the background of the cell correctly depending on its value. But I need to colour the entire row, but I cannot get this to work. If I change CellStyle to RowStyle and TargetType to DataGridRow, then it doesn't colour any cells.

Upvotes: 0

Views: 222

Answers (1)

VijayKP
VijayKP

Reputation: 321

If I understand it correctly, you are trying to set the color of the row depending on the value present in some column.

The reason why it is not working for DataGridRow is it does not contain Column.DisplayIndex property.

You may like to try the following.

<DataGrid.RowStyle>
    <Style TargetType="DataGridRow">
        <Setter Property="Background" Value="{Binding Path=yourPropertyName, Converter={StaticResource vjColorConverter}}"></Setter>
    </Style>
</DataGrid.RowStyle>

Instead of trying to read the Value from the column's content, directly get it from the DataContext itself. DataContext is the one to which your DataGrid is bound to fill the rows. For your case it is the property name of the 11th Display Column.

Upvotes: 1

Related Questions