【问题标题】:WPF DataGrid - highlight Selected row even when SelectedItem is a bound propertyWPF DataGrid - 即使 SelectedItem 是绑定属性,也会突出显示选定行
【发布时间】:2015-01-18 15:45:27
【问题描述】:

我有一个 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 上的绑定,它会按预期工作。无论绑定如何,我怎样才能使这项工作?

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:

    我自己找到了答案,滚动浏览 Intellisense for SystemColors。您也可以覆盖一个 InactiveSelection 画笔。

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

    【讨论】:

    • 这里还有一个有趣的小技巧:&lt;SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="{DynamicResource {x:Static SystemColors.HighlightColorKey}}"/&gt; 这将使非活动设置为活动,无论默认设置或必须更改突出显示键。
    • InactiveSelectionHighlightBrushKey 仅适用于 FW 4.5,并在 FW 4.0 中引发异常。请查看stackoverflow.com/a/13827971/1815957
    猜你喜欢
    • 2013-06-11
    • 2015-10-31
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 2013-12-20
    • 2012-10-12
    相关资源
    最近更新 更多