WPF DataGrid失去了对ContextMenu的关注

时间:2021-12-03 22:16:37

My DataGrid has a ContextMenu assigned which contains commands to do something with the selected row(s). That works fine already.

我的DataGrid分配了一个ContextMenu,其中包含对所选行执行某些操作的命令。这已经很好了。

The problem is, every time the ContextMenu is opened (either by right mouse button or menu key), the DataGrid loses its focus and the selected row changes its background colour from blue to light grey. That's so much of a contrast that the user gets the impression that the selection is cleared and isn't sure if the context menu opens for the correct row.

问题是,每次打开ContextMenu时(通过鼠标右键或菜单键),DataGrid都会失去焦点,所选行会将其背景颜色从蓝色变为浅灰色。这是一个很大的对比,用户会得到清除选择的印象,并且不确定上下文菜单是否为正确的行打开。

That colour change is perfectly fine, a non-focused item should not have a focus colour. But opening a context menu just shouldn't trigger it.

颜色变化非常好,非聚焦项目不应该有焦点颜色。但打开上下文菜单不应该触发它。

Here's some XAML code:

这是一些XAML代码:

<DataGrid
    HeadersVisibility="Column"
    HorizontalGridLinesBrush="#cccccc" VerticalGridLinesBrush="#cccccc"
    BorderBrush="#cccccc" Background="{x:Null}"
    CanUserReorderColumns="False" IsReadOnly="True"
    ItemsSource="{Binding MyItems, NotifyOnTargetUpdated=True}"
    AutoGenerateColumns="False"
    SelectionChanged="DataGrid_SelectionChanged">
    <DataGrid.Columns>
        <DataGridTextColumn .../>
        <DataGridTextColumn .../>
        <DataGridTextColumn .../>
    </DataGrid.Columns>
    <DataGrid.ContextMenu>
        <ContextMenu DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
            <MenuItem Header="Command text" Command="{Binding MyCommand}"/>
        </ContextMenu>
    </DataGrid.ContextMenu>
</DataGrid>

And the annotated screenshot of the issue:

以及该问题的带注释的屏幕截图:

WPF DataGrid失去了对ContextMenu的关注

How can I fix that?

我该如何解决这个问题?

1 个解决方案

#1


3  

Since I just happened to have the same problem, I found the solution (for me) in another question on SO: Retain DataGrid IsSelectionActive when a ContextMenu opens in WPF?

由于我碰巧遇到了同样的问题,我在另一个问题上找到了解决方案(对我来说):当一个ContextMenu在WPF中打开时,保留DataGrid IsSelectionActive?

I just copied the DataGridCell style into my code and it worked.

我只是将DataGridCell样式复制到我的代码中并且它有效。

#1


3  

Since I just happened to have the same problem, I found the solution (for me) in another question on SO: Retain DataGrid IsSelectionActive when a ContextMenu opens in WPF?

由于我碰巧遇到了同样的问题,我在另一个问题上找到了解决方案(对我来说):当一个ContextMenu在WPF中打开时,保留DataGrid IsSelectionActive?

I just copied the DataGridCell style into my code and it worked.

我只是将DataGridCell样式复制到我的代码中并且它有效。