Search code examples
wpfcontextmenuselecteditemright-clickxceed-datagrid

Xceed extended WPF datagrid select row with right click


I am trying to add a context menu to an Xceed extended WPF datagrid. I am able to show the context menu and the commands fire from the menu, but right clicking on a row does not set it as the selected row and so the wrong record is used by the command.

Is there a way to change the way the selected item is set so that it can be updated by right click?

<xcdg:DataGridControl ItemsSource="{Binding Source={StaticResource RecordsForList}}" SelectedItem="{Binding SelectedRecord}">
    <xcdg:DataGridControl.ContextMenu>
        <ContextMenu>
            <MenuItem Command="{Binding OpenCommand}" Header="Open" />
        </ContextMenu>
    </xcdg:DataGridControl.ContextMenu>
</xcdg:DataGridControl>

Solution

  • Instead of changing the way selecting an item works, you could pass the current item as a command parameter to the command if you set the ContextMenu property of each individual DataRow:

    <xcdg:DataGridControl ItemsSource="{Binding Source={StaticResource RecordsForList}}" SelectedItem="{Binding SelectedRecord}">
        <xcdg:DataGridControl.ItemContainerStyle>
            <Style TargetType="xcdg:DataRow">
                <Setter Property="Tag" Value="{Binding DataContext, RelativeSource={RelativeSource AncestorType=xcdg:DataGridControl}}" />
                <Setter Property="ContextMenu">
                    <Setter.Value>
                        <ContextMenu>
                            <MenuItem Command="{Binding PlacementTarget.Tag.OpenCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
                                      CommandParameter="{Binding}" Header="Open" />
                        </ContextMenu>
                    </Setter.Value>
                </Setter>
            </Style>
        </xcdg:DataGridControl.ItemContainerStyle>
    </xcdg:DataGridControl>
    

    The other option would be to write some code in the view that actually selects an item on right-click, e.g.:

    <xcdg:DataGridControl ItemsSource="{Binding Source={StaticResource RecordsForList}}"  SelectedItem="{Binding SelectedRecord}">
        <xcdg:DataGridControl.ContextMenu>
            <ContextMenu>
                <MenuItem Command="{Binding OpenCommand}" Header="Open" />
            </ContextMenu>
        </xcdg:DataGridControl.ContextMenu>
        <xcdg:DataGridControl.ItemContainerStyle>
            <Style TargetType="xcdg:DataRow">
                <EventSetter Event="PreviewMouseRightButtonDown" Handler="xgrid_PreviewMouseRightButtonDown" />
            </Style>
        </xcdg:DataGridControl.ItemContainerStyle>
    </xcdg:DataGridControl>
    

    private void xgrid_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {
        Xceed.Wpf.DataGrid.DataRow row = sender as Xceed.Wpf.DataGrid.DataRow;
        xgrid.CurrentItem = row.DataContext;
    }