Cómo obtener el elemento seleccionado en el menú contextual

I have a context menu that has binding items and I want to set up a command and command parameter so I know which item was clicked on but I don't know how.

<MenuItem Command="{Binding Sync}"   
  Header="Synchronize" 
  ItemsSource="{Binding ItemsToSync}">
  <MenuItem.Icon>
      <Image Height="25" Source="Sync.png" />
  </MenuItem.Icon>
</MenuItem>

preguntado el 31 de julio de 12 a las 14:07

2 Respuestas

You can try something like this: In this example I have a listview and I can right click and delete a selected item. The Reason I'm using RelativeSource here is because when it comes to passing parameters in menuitems, most of the time at this level you can't reach the datacontext of the page. Hope this helps.

               <ListView.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="Delete" Command="{Binding Path=DeleteDescriptions}" CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.SelectedItem}" Name="MenuItem1">
                        </MenuItem>
                    </ContextMenu>
                </ListView.ContextMenu>

Respondido 31 Jul 12, 16:07

That did not help but I was able to create my own solution.

 <MenuItem Header="Synchronize" ItemsSource="{Binding ItemsToSync}">
                    <MenuItem.Icon>
                        <Image Height="25" Source="Sync.png" />
                    </MenuItem.Icon>
                    <MenuItem.ItemContainerStyle>
                        <Style>
                            <Setter Property="MenuItem.Header" Value="{Binding Name}" />
                            <Setter Property="MenuItem.IsChecked" Value="{Binding IsCurrent}" />
                            <Setter Property="MenuItem.Command" Value="PT:Commands.SyncFromContextMenu" />
                            <Setter Property="MenuItem.CommandParameter" Value="{Binding}" />
                        </Style>
                    </MenuItem.ItemContainerStyle>

                </MenuItem>
</MenuItem>

I did have to create a static class for the command.

Respondido 31 Jul 12, 16:07

Always best when you can find the solution yourself. Why did you have to make a static class for your command though? - Tman

Not exactly sure though, I'll keep you updated, I plan on getting rid of that in my next step. - leah smith

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.