所选行的WPF DataGrid RowStyle不改变背景和前景色

标签 wpf datagrid background-color

我在 Windows 7 上使用 Visual Studio 2012。我需要知道为什么 Grid 所选行的以下样式不适用于背景和前景色,但对于其他属性(例如 BorderBrush 和 BorderThickness 等)却完全适用?虽然我可以看到它们在鼠标悬停在网格行上时发生变化。

<Style x:Key="gridRowStyle" TargetType="{x:Type DataGridRow}">
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="PeachPuff"/>
            <Setter Property="Foreground" Value="BlueViolet"/>
        </Trigger>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background" Value="PeachPuff"/>
            <Setter Property="Foreground" Value="BlueViolet"/>
            <Setter Property="BorderBrush" Value="BlueViolet" />
            <Setter Property="BorderThickness" Value="2" />

        </Trigger>
    </Style.Triggers>
</Style>

这是我在网格上的使用方式。
<DataGrid RowStyle="{StaticResource gridRowStyle}">

我强调知道“为什么”而不是问题的解决方案,因为如果我使用网格单元格样式而不是如下所示的行样式,我已经有了问题的解决方案:
<Style x:Key="gridCellStyle" TargetType="{x:Type DataGridCell}">
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background" Value="PeachPuff"/>
            <Setter Property="Foreground" Value="BlueViolet"/>
        </Trigger>
    </Style.Triggers>
</Style>

最佳答案

在具有以下默认样式触发器的 DataGridCell 的默认样式中。

<Trigger Property="IsSelected" Value="True">
    <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
    <Setter Property="BorderBrush" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
</Trigger>

因此,如果您为 DataGridRow 编写触发器,那么它只会应用于可视化树中放置在 DataGridCell 之前的元素。

因此,要在选择时更改背景和前景,您必须以 DataGridCell 样式编写触发器或从样式中删除默认触发器。

关于所选行的WPF DataGrid RowStyle不改变背景和前景色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14876223/

相关文章:

C# WPF Datagrid 不会在数据更新时动态排序

c++ - QPushButton 背景颜色重叠边框

css - 突出显示元素然后过渡回原始颜色

wpf - UI线程 block

c# - 你如何从xaml传递参数?

wpf - DataGrid WPF 中的 OnScrollShow 事件

css - 移动设备和桌面设备上的 Prestashop css 问题

wpf - 正确的 MVVM 设计模式 - ViewModel 和 DataContext

c# - RenderTransform RotateTransform 模糊图像

c# - 防止在 DataGrid 中按下回车键时自动更改行