79459069

Date: 2025-02-22 04:18:08
Score: 1
Natty:
Report link

Is this the same problem?:WPF DataGrid : Avoid Cell selection on RightClick

<DataGrid x:Name="MyDataGrid"
          PreviewMouseRightButtonDown="DataGrid_PreviewMouseRightButtonDown"
          SelectionChanged="MyDataGrid_SelectionChanged"
          SelectionMode="Extended"
          SelectionUnit="FullRow">
    <DataGrid.Resources>
        <!-- Focus: Modify CellStyle, not RowStyle. -->
        <Style TargetType="DataGridCell">
            <Style.Triggers>
                <!-- Normal highlighting when left-click selected -->
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="Background" Value="{DynamicResource YourBrush}" />
                    <Setter Property="BorderBrush" Value="{x:Null}" />
                    <Setter Property="BorderThickness" Value="1" />
                    <Setter Property="Foreground" Value="{DynamicResource YourBrush}" />
                </Trigger>

                <!-- Transparent background when right-clicking to avoid highlighting -->
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="Background" Value="Transparent" />
                    <Setter Property="BorderThickness" Value="0" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </DataGrid.Resources>

    <DataGrid.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Your Header" Click="MenuItem_Click"/>
        </ContextMenu>
    </DataGrid.ContextMenu>
</DataGrid>
private object? _previouslySelectedItem;
private bool _isRightClick = false;

private void DataGrid_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    if (e.OriginalSource is DependencyObject dep)
    {
        var cell = FindVisualParent<DataGridCell>(dep);
        if (cell != null)
        {
            _isRightClick = true;
            _previouslySelectedItem = MyDataGrid.SelectedItem;

            // Probably not.:
            // Keyboard.ClearFocus();
        }
    }
}

private void MyDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (_isRightClick)
    {
        MyDataGrid.SelectedItem = _previouslySelectedItem;
        _isRightClick = false;
    }
}

private static T? FindVisualParent<T>(DependencyObject child) where T : DependencyObject
{
    while (child != null)
    {
        if (child is T parent)
            return parent;

        child = VisualTreeHelper.GetParent(child);
    }
    return null;
}
Reasons:
  • Probably link only (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Starts with a question (0.5): Is this the
  • Low reputation (0.5):
Posted by: CodingNinja