WPF contextmenu and ListView
Ok, hopefully this is simple but for some reason I can't find a straight answer and I'm not familiar enough with WPF yet to know how to do it.
I have a listview, it gets bound to an observable collection of objects to display. I want to have a context menu with a bunch of options. The options in the context menu are relative to the particular object in the list that was clicked on (things like delete, export, etc).
So I need the object that the user right clicked on in my listview to be passed as a parameter to the command that the context menu executes.
How do I do this?
Edit: I should mention I would prefer a solution that is mostly (if not entirely) xaml - I'm trying to avoid having s开发者_开发知识库ignificant code in the code-behind. If that's the only way to do it though...
Further Edit: More details that I forgot to mention that are important. The command I want executed is on the object bound to the data context of my user control, it is not on the objects in the list view. So I need the context menu's on the list view's items to be bound to a command that is on the user control's data context, and the listview item passed as a parameter into that command.
It depends on whether your ContextMenu
is part of the template for individual items, or if it is attached to the ListBox as a whole.
If you are attaching your ContextMenu
to the items in the list using a DataTemplate (this is generally the best way to do it), the DataContext
on the MenuItem
is already set so all you need to do is:
<MenuItem ... CommandParameter="{Binding}" />
On the other hand, if your ContextMenu
is attached to the ListBox
as a whole, you'll need to access the SelectedItem
property of the ListBox
:
<MenuItem ... CommandParameter="{Binding SelectedItem, RelativeSource={RelativeSource FindAncestor,ListBox,1}} />
精彩评论