views:

713

answers:

3

How can the handler method of a WPF menu item determine which item in a ListView was clicked on?

Edit: The menu is a context menu which has been set for the ListView. The problem is to find which ListView item has been clicked on when the context menu item is selected.

+1  A: 

Checkout ContextMenu.PlacementTarget, which that object you can walk up the visual tree (VisualTreeHelper.GetParent) until you find a ListViewItem.

Martin Moser
A: 

If each of your data items has an IsSelected property that is bound to the ListViewItem.IsSelected property, then you just iterate through your data to find the selected ones:

<ListView ItemsSource="{Binding Items}">
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
             <Setter Property="IsSelected" Value="{Binding IsSelected}"/>
        </Style>
    </ListView.ItemContainerStyle>
</ListView>

And in your code:

public ICollection<DataItem> Items
{
    get { return _items; }
}

public IEnumerable<DataItem> SelectedItems
{
    get
    {
         foreach (var item in Items)
         {
             if (item.IsSelected)
                 yield return item;
         }
    }
}

private void DoSomethingWithSelectedItems()
{
    foreach (var item in SelectedItems) ...
}

HTH, Kent

Kent Boogaart
A: 

Just in case anyone else has this problem, I ended up with something like:

private void ListViewItems_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
   var frameworkElement = e.OriginalSource as FrameworkElement;

   var item = frameworkElement.DataContext as MyDataItem;

   if(null == item)
   {
      return;
   }

   // TODO: Use item here...
}
Thomas Bratt