DataHridRowStyle由RowHighlightBrush

时间:2017-07-05 10:16:44

标签: c# wpf xaml datagrid

我有一个DataGridStyle,它根据名为ApprovalLevel的值修改其TextBlock的Foreground属性。它看起来像这样:

<Style TargetType="{x:Type DataGridRow}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding ApprovalLevel}" Value="-1">
            <Setter Property="Foreground" Value="Red"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding ApprovalLevel}" Value="0">
            <Setter Property="Foreground" Value="Black"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding ApprovalLevel}" Value="1">
            <Setter Property="Foreground" Value="Green"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding ApprovalLevel}" Value="2">
            <Setter Property="Foreground" Value="Blue"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

这会将样式应用于行而不会出现问题,但是当用户突出显示该行时,样式将被覆盖并且前景色将丢失。我尝试过应用以下样式:

<DataGrid.Resources>
    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/>
</DataGrid.Resources>

然而,所有这一切都将整个行覆盖为透明。我的问题是如何向用户说明他们选择了一行,同时保留了我想申请的前景风格?

1 个答案:

答案 0 :(得分:0)

使用TextBlock设置ElementStyle的样式,而不是使用DataGridRow样式:

<DataGrid x:Name="dg">
    <DataGrid.Resources>
        <Style x:Key="style" TargetType="{x:Type TextBlock}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ApprovalLevel}" Value="-1">
                    <Setter Property="Foreground" Value="Red"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding ApprovalLevel}" Value="0">
                    <Setter Property="Foreground" Value="Black"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding ApprovalLevel}" Value="1">
                    <Setter Property="Foreground" Value="Green"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding ApprovalLevel}" Value="2">
                    <Setter Property="Foreground" Value="Blue"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding YourProperty}" ElementStyle="{StaticResource style}" />
        <!-- ... -->
    </DataGrid.Columns>
</DataGrid>