【问题标题】:Change entire row colour, not just cell更改整行颜色,而不仅仅是单元格
【发布时间】:2013-12-15 23:08:10
【问题描述】:

我在 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,那么它不会为任何单元格着色。

【问题讨论】:

    标签: wpf datagrid


    【解决方案1】:

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

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

    您可能想尝试以下方法。

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

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

    【讨论】:

    • 感谢您的帮助。我不知道我在哪里声明应该颜色。我今天早上才开始研究 WPF,需要阅读更多相关信息。
    • 已编辑删除不需要的 DataTrigger。
    • 我无法让它工作。我现在已经在 WinForms 中创建了这个(对我来说容易多了!)。我以为我选择了一个简单的项目来开始学习 WPF,但它对我来说太陌生了。我真的需要一本关于它的书。谢谢你的帮助。无论如何,我已将您的答案标记为答案。
    猜你喜欢
    • 2017-06-28
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多