Right-click options menu in selected row in datagrid

2
Hello, I have the following problem: I have several records in datagrid and I want the moment I select a record and right click on it, a menu with options for the selected line appears. The only options in this menu are delete, details and print. I tried a solution that passed me another question that I did, but it did not work, because it enabled the menu anywhere in the datagrid that I clicked with the right mouse button.

    
asked by anonymous 26.05.2015 / 15:38

2 answers

2

In order for ContextMenu to only appear when a line is selected, add this ItemContainerStyle to your ContextMenu

<ContextMenu.ItemContainerStyle>
    <Style TargetType="{x:Type MenuItem}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.SelectedItems.Count}" Value="0">
                <Setter Property="Visibility" Value="Collapsed" />
            </DataTrigger>
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.SelectedItems.Count}" Value="1">
                <Setter Property="Visibility" Value="Visible" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</ContextMenu.ItemContainerStyle>  

The most correct would be ContextMenu appear with your disabled items:

<ContextMenu.ItemContainerStyle>
    <Style TargetType="{x:Type MenuItem}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.SelectedItems.Count}" Value="0">
                <Setter Property="IsEnabled" Value="False" />
            </DataTrigger>
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.SelectedItems.Count}" Value="1">
                <Setter Property="IsEnabled" Value="True" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</ContextMenu.ItemContainerStyle>
    
26.05.2015 / 16:47
0

You need to create a ContextMenu in your datagrid and put the options in it. It looks something like this:

<DataGrid Name="dataGrid">
    <DataGrid.ContextMenu>
       <ContextMenu>
          <MenuItem Header="Excluir" Click="MenuItemExcluir_Click"/>
          <MenuItem Header="Detalhes" Click="MenuItemDetalhes_Click"/>
          <MenuItem Header="Imprimir" Click="MenuItemImprimir_Click"/>
       </ContextMenu>
    </DataGrid.ContextMenu>
</DataGrid>

For each action in this menu will have a Click event, in it you will be able to identify which item was clicked and continue processing what you need to do.

    
26.05.2015 / 16:22