My DataGrid has a ContextMenu assigned which contains commands to do something with the selected row(s). That works fine already.
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.
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:
<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:
How can I fix that?
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?
I just copied the DataGridCell style into my code and it worked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With