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?