|
I have a set of classes for working with menus that are quite like SoapBox's MenuItem classes. I don't have a context menu yet but I stumbled upon the SoapBox implementation and it seems ok, but cannot get it to work. I also found no sample of how to use it. Here's what I tried: First I added all related classes to my project, and removed the Export attribute from ContextmenuView and ContextMenuWrapperView. Then provide a working implementation for IContextMenu:
I changed the ContextMenuWrapperView.xaml to have a style key:
And put a ContextMenu in the xaml for a usercontrol on which I want a ContextMenu shown.
The DataContext of the usercontrol is set to a VM that has the context menu VM as a property:
The menu is populated with a couple of items, but when running this I can see a ContextMenuWrapper being instantiated, followed by a call to MyContextMenu, and ContextMenuWrapperView/ContextMenuView are instantiated as well, but the only thing shown upon right-clik is a menu with one empty item. Any input would be greatly appreciated!
showing 5 of 6
show all
|
If you've removed the Export attribute from the
ContextMenuView, then how are you making sure that WPF is going to apply the View to the ViewModel? Did you add the type specifier to theDataTemplate?I set an x:Key on the style in ContextMenuWrapperView.xml and applied it to the wrapper but it doesn't change anything. I updated the question to reflect this.
@stijn - try setting the
DataTemplate.DataTypeproperty to yourViewModeltype, and also make sure that the data template is included (through a merged dictionary) in your App.xaml's resource dictionaries.@ScottWhitlock apologies but I'm afraid I'm too new to this. I don't see any DataTemplate to set the property on, let alone that I understand why it's needed. To start from the beginning: is the code above, especially the xaml, the correct starting point? Cause it seems weird having the ContextMenuWrapper inside the ContextMenu element.
@stijn - I believe by putting the
ContextMenuWrapper(which is a ViewModel) directly into the visual tree like this, WPF will check for any declared DataTemplates that have the DataType attribute set to the ViewModel's type. Then instead of putting the ViewModel directly into the visual tree, it instantiates an instance of the DataTemplate, and sets the DataContext to the ViewModel. That means the controls in the DataTemplate are what you actually see. I know this works for ContentControls, but inside a context menu, I'm a little shaky.sorry for the late reply, I was doing other stuff. Anyway I tried a couple of things but could'nt get the DataTemplate to work. I got a working solution without using templates though by just binding the ContextMenu to a List<imenuitem> in the VM..