首页 > 解决方案 > 如果特定值在行内,则更改行中的背景颜色

问题描述

我在更改 Datagrid 中行的颜色时遇到了一些麻烦。

我的 Datagrid 有一个 DataView 作为源。DataView 从 SQL 查询中获取它的值。(有几个 SQL 查询,所以 DataView 的内容和它的列是不同的)。

现在我的问题是,如果 DataView 中的值是特定字符串,我必须更改行的背景颜色。例如:如果字符串的值是“信息”,那么它应该是背景色“蓝色”,如果值是“错误”,那么它应该是红色。

我的 DataGrid 看起来像这样:

<DataGrid ItemsSource="{Binding GetDataView}"
                      Foreground="White"
                      Style="{DynamicResource DataGridStyle2}"
                      RowHeaderWidth="0"
                      BorderThickness="1"
                      HorizontalGridLinesBrush="#FF9A969E"
                      VerticalGridLinesBrush="#FF9A969E"
                      RowBackground="{x:Null}"
                      HorizontalAlignment="Stretch"
                      Margin="10,0,10,30"
                      Grid.Row="3"
                      VerticalAlignment="Stretch">
            </DataGrid>

DataView 的“AutoGenereatedColumns”如下:ID、名称、注释、级别、日期。

我的问题是我不知道要创建触发器,所以它可以对“级别”的值做出反应,因为它是自动生成的。

标签: c#xamldataview

解决方案


您需要一个用于行样式的数据触发器。

<DataGrid Name="dataGrid1" Margin="12,12,0,0">
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="Background" Value="LightBlue" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding Level}" Value="somestring">
                    <Setter Property="Background" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

像这样的东西。

(未经测试,但应该可以工作)

更多信息


推荐阅读