0

I have a list view that's populated with items. Each of these items has a ContextMenu attached to it. When a user right clicks on one of these items in the ListView and clicks one of the buttons in the ContextMenu I need to get the name of the item in the ListView that was clicked.

My XAML for the ListView looks like this:

<ListView.Resources>
    <ContextMenu x:Key="ItemContextMenu">
        <MenuItem Click="Download" Header="Download" Command="{Binding Path=DataContext.MoreInfo, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListView}}" Background="WhiteSmoke" />
    </ContextMenu>
</ListView.Resources>

<ListView.ItemContainerStyle>
    <Style TargetType="{x:Type ListViewItem}" >
        <Setter Property="ContextMenu" Value="{StaticResource ItemContextMenu}" />
    </Style>
</ListView.ItemContainerStyle>

When I right click and click the MenuItem called "Download", the Download() function is called.

Here's the code for Download():

private void Download(object sender, RoutedEventArgs e)
{
    ListViewItem selectedItem = list.SelectedItem as ListViewItem;
    Console.WriteLine("Download clicked!");
    if (selectedItem == null)
    {
        Console.WriteLine("It's nothing!");
    }
}

The selected item from the ListView is always null. Is it because when the user right clicks to bring up the context menu the ListViewItem is no longer technically selected? How do I fix this?

Crisp Apples
  • 267
  • 1
  • 2
  • 13

1 Answers1

1

You can utilize the PlacementTarget to get the ContextMenu's parent.

The PlacementTarget is a DependencyProperty that allows you to reference the Visual Tree that holds the invoked ContextMenu.

When the ContextMenu is assigned to the FrameworkElement.ContextMenu or FrameworkContentElement.ContextMenu property, the ContextMenuService changes this value of this property to the owning FrameworkElement or FrameworkContentElement when the ContextMenu opens. To use a different UIElement, set the ContextMenuService.PlacementTarget property.

See: MSDN

private void Download(object sender, RoutedEventArgs e)
{
    // Note: In this case, the `sender` parameter is the MenuItem as well.
    // MenuItem menuItem = sender as MenuItem

    MenuItem menuItem = e.Source as MenuItem;
    ContextMenu menu = menuItem.Parent as ContextMenu;
    ListViewItem item = menu.PlacementTarget as ListViewItem;

   if (item != null)
   {
       Console.WriteLine(item.Name);
   }
}
Michael G
  • 6,695
  • 2
  • 41
  • 59