WPF数据表格 - 即使SelectedItem是绑定属性,也要突出显示选定行

6
我有一个WPF DataGrid,其中SelectedItem与ViewModel属性绑定。
SelectedItem="{Binding DataContext.SelectedBooking, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" 

如果用户点击一行,选择它,唯一的视觉线索是该行的灰色背景变得非常轻微。我需要让这更加明显,因此我尝试单独添加以下内容:

<DataGrid.RowStyle>
    <Style TargetType="{x:Type DataGridRow}">
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Foreground" Value="Red"/>
                <Setter Property="Background" Value="Red" />
            </Trigger>
        </Style.Triggers>
    </Style>
</DataGrid.RowStyle>

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

结果是一样的。当用户单击一行时,它会短暂地闪红,然后回到苍白的灰色,尽管该行实际上仍然被选中。如果他们第二次点击它,它就会变成红色并保持红色。
如果我删除SelectedItem上的绑定,它将按预期工作。如何使其无论绑定如何都能正常工作?
1个回答

7
我在Intellisense中找到了答案,有一个InactiveSelection brush可以覆盖。
<DataGrid.Resources>
    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Red"/>
    <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Red"/>
</DataGrid.Resources>

1
这里有一个有趣的小技巧,你可以这样做: <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="{DynamicResource {x:Static SystemColors.HighlightColorKey}}"/> 这将使得非活动状态变为活动状态,无论默认情况还是需要更改高亮键。 - Khale_Kitha
InactiveSelectionHighlightBrushKey 只适用于 FW 4.5 并且在 FW 4.0 中会抛出异常。请查看 https://dev59.com/imYr5IYBdhLWcg3wRoOW#13827971。 - diedie2
感谢您的回答和评论!在我的情况下,我不得不通过结合#Bob和#Khale的答案来改变颜色,并添加了:<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightTextBrushKey}" Color="White" />以获得字体的对比度。换句话说,我改变了前景色。 - omostan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接