Question

First take a look at my code:

<ListBox ItemsSource="{Binding}" SelectionMode="Multiple"
    ItemTemplate="{StaticResource ContactTemplate}">
    <ListBox.ContextMenu>
        <ContextMenu>
            <MenuItem Name="mnuEdit" Header="_Edit" Click="MenuItem_Click" />
        </ContextMenu>
    </ListBox.ContextMenu> 
</ListBox>

I want, the when the user right-clicks an individual ListBoxItem in the ListBox, it should be passed (or the index of it or whatever a way to find the item that the ContextMenu popped-out on.

Was it helpful?

Solution

You need to define ItemContainerStyle or ItemsTemplate for the ListBox and add ContextMenu there. Now you will be inside the SelectedValue(DataContext)

You can set the Contextmenu for your 'ContactTemplate', so that when you right click your ContextMenu will have the Data on which you clicked(From MenuItem.DataContext)

Another way, which assumes your rightclick might have already set that ListBoxItem as the Selected. In Menu Click event you can get the SelectedIndex by ((FrameworkElement)sender).DataContext

<MenuItem DataContext="{Binding ElementName=lstBox,Path=SelectedIndex}" ..../> 

OTHER TIPS

Try this:

private void MenuItem_Click(object sender, RoutedEventArgs e) {

  var listItem = (((FrameworkElement)sender)).DataContext;  //Cast however you want
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top