WPF数据网格:如何保持选中的行突出显示

本文关键字:显示 何保持 数据网 数据 网格 WPF | 更新日期: 2023-09-27 18:07:04

我在WPF项目的同一个窗口上有多个DataGrid控件。当我单击网格中的一行时,它会高亮显示。当我单击另一个网格中的一行时,该行高亮显示,而第一个网格中的行变得非常微弱高亮。如何设计此窗口,以便每个网格可以同时突出显示所选的行?我的项目是在。net 4.0中构建的,所以InactiveSelectionHighlightBrushKey似乎不起作用。我使用下面的代码,它基本上工作,除了当我点击一个不同的网格,前一个网格改变行文本的颜色为黑色而不是白色。我尝试将ControlTextBrushKey设置为白色,但这使得网格中的每一行都变成白色,这意味着未选中的行因为不可见,因为背景也是白色的。是否有一种更优雅的方法,通过创建用户控件或从DataGrid类继承来实现这一点,因为我需要在项目中多次插入此代码。

                <DataGrid Name="dgStores" >
                    <DataGrid.Resources>
                        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="{x:Static Colors.DodgerBlue}"/>
                        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="White"/>
                        <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="{x:Static Colors.DodgerBlue}"/>
                    </DataGrid.Resources>
                </DataGrid>

WPF数据网格:如何保持选中的行突出显示

使用Style.Triggers设置DataGridCell的IsSelected颜色。

<Window.Resources>
    <Style TargetType="{x:Type DataGridCell}">
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Background" Value="{x:Static SystemColors.HighlightBrush}"></Setter>
                <Setter Property="Foreground" Value="{x:Static SystemColors.HighlightTextBrush}"></Setter>
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

试试这个:

<DataGrid ItemsSource="{Binding Items}">
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="Background" Value="White" />
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="Background" Value="Blue"/>
                    <Setter Property="Foreground" Value="White"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>