WPF DataGrid - 即使 SelectedItem 是绑定属性,也突出显示选定的行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27045396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:42:49  来源:igfitidea点击:

WPF DataGrid - highlight Selected row even when SelectedItem is a bound property

c#wpfdatagrid

提问by Bob Tway

I've got a WPF DataGrid where the SelectedItem is bound to a ViewModel property.

我有一个 WPF DataGrid,其中 SelectedItem 绑定到 ViewModel 属性。

SelectedItem="{Binding DataContext.SelectedBooking, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" 

If a user clicks on a Row, selecting it, the only visual clue is that the gray background of the row becomes very slightly lighter. I need to make this more obvious, so I tried adding these, individually:

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

<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>

And

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

The result is the same. When a user single-clicks on a row it very briefly flashes red and then goes back to pale gray, although the Row actually remains as being Selected. If they click on it a second time, it goes red and stays red.

结果是一样的。当用户单击一行时,它会非常短暂地闪烁红色,然后返回浅灰色,尽管该行实际上仍处于选中状态。如果他们第二次点击它,它会变成红色并保持红色。

If I remove the Binding on SelectedItem, it works as expected. How can I make this work regardless of the Binding?

如果我删除 SelectedItem 上的绑定,它会按预期工作。无论绑定如何,我怎样才能使这项工作?

回答by Bob Tway

I found the answer myself, scrolling through the Intellisense for SystemColors. There's an InactiveSelection brush that you can override too.

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

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