How to bind a context menu to a list in the VM ?

Feb 27, 2011 at 11:16 PM


I am trying to create a context menu, populated by items from a list in my view model. (I'm working in WPF)

I've found similar discussions (like, but so far I can't find a simple explanation or working example of how to do it.

I have a listbox containing items, and the menu items available in the context menu will depend on the item selected.

So, my  ViewModel has a method, AvailableCommands, which for now, is a list of strings, representing the names of the commands available for the item.

I think I was assuming I could bind the ContextMenu to this list - something along the lines of :-

<ContextMenu Name="AvailableCommands"  ...    <- in the hope that the conventions would find it, or
<ContextMenu ItemsSource="{Binding AvailableCommands}"  ...  <- binding it myself, and then having an ItemContainerStyle if necessary, to bind the name, and the command to invoke.

So far, I seem to be just getting a tiny empty box when I right click, which I guess means it's not finding anything to bind to.. ? (The list coming from my ViewModel is not empty, as far as I can see !)

Any thoughts on how this should be done ?

thanks ! :)

Feb 28, 2011 at 2:07 AM

The problem with ContextMenu only affects action bubbling, so you shouldn't have any problem to bind properties (which I guess AvailableCommands is - even though you wrote "method").

Where does the context menu live? At listbox level or in the listbox  ItemsTemplate ?

Feb 28, 2011 at 4:30 AM

Thank you so much ! :)

My method was in fact a method, rather than a property.

I've changed it to a property, and now it works.

(I think this is my Java background showing !)

So, I now have :-

<ContextMenu ItemsSource="{Binding AvailableCommands}" >

The context menu is dependent on each item, rather than the listbox, So, the listbox actually contains a list of ListItemViewModels.
ListItemViewModel has the AvailableCommands property, which returns the list of available commands based on the state of the item etc.


Thanks again :)