更改整行的颜色,而不仅仅是单元格



我在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>

这个类别:

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();
  }
}

这将根据单元格的值正确地为其背景着色。但我需要给整排涂上颜色,但我无法做到这一点。如果我将CellStyle更改为RowStyle,将TargetType更改为DataGridRow,那么它不会给任何单元格上色。

如果我理解正确,您将尝试根据某列中的值设置行的颜色。

它不适用于DataGridRow的原因是它不包含Column.DisplayIndex属性。

您可以尝试以下操作。

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

与其尝试从列的内容中读取Value,不如直接从DataContext本身获取它。DataContext是绑定DataGrid以填充行的上下文。对于您的情况,它是第11个显示列的属性名称。

相关内容

最新更新