WPF DataGrid loses focus on ContextMenu

My DataGrid has an assigned ContextMenu that contains commands for doing anything with the selected rows. This already works great.

The problem is that every time ContextMenu opens (either with the right mouse button or the menu key), the DataGrid loses focus and the selected row changes its background color from blue to light gray. This contrasts so much that the user gets the impression that the selection is cleared and not sure if the context menu opens for the correct line.

That the color change is absolutely beautiful, the unfocused element should not have the color of focus. But opening the context menu simply should not start it.

Here is some XAML code:

<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 annotated screenshot:

Screen shot

How can i fix this?

+4
1
+2

Source: https://habr.com/ru/post/1527461/


All Articles