I am writing a C# application using WFP and the MVVM pattern.
In my view, I have a TreeView and each Item in that Tree View has its own Context Menu displayed when the user right clicks. The behavior I want a SubMenu within the Context Menu's Menu item that also allows for an Item Source to be supported.
Here is a text version of what I'd like: ContextMenu (items sourced from an Item Source) MenuItem_A (item sourced from an Item Source) SubMenuItem_A MenuItem_B (might not have any sub-items)
Here's what I tried:
<TreeView x:Name="MyTreeView" Tag={Binding ElementName=MyTreeView, Path=DataContext}>
<TreeView.ItemTemplate>
<HeriarachicalDataTemplate DataType={x:Type namespace:ItemsViewModel}
<Grid>
<Grid.ContextMenu>
<ContextMenu
DataContext={Binding Path=PlacementTarget.Tag, RelativeSouce={Self}} ItemSource ={Binding HostedMenuOptions}>
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Header" Value={Binding HostedMenuItemName}>
<Setter Property="ItemsSource" Value={Binding RelativeSource={RelativeSource FindAcestor, AncestorType={x:TYpe ContextMenu}}, Path=DataContext.HostedMenuItemSubMenus}/>
</Style>
</ContextMenu.ItemContainerStyle>
</Grid.ContextMenu>
</Grid>
</HerarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
The error that I'm seeing is an xaml binding error: HostedMenuItemName property not found on object of RunTimeType
Is there another way to achieve this? Basically I want the contextmenu, menus and submenus to to be determined by lists of objects that are stored in the ViewModel.
Here's some experimental markup I tried.
I have a treeview which is bound to a collection of family which itself has family members.
As a quick and dirty experiment I added a class MenuThing
In my treeview resources I define a contextmenu as a resource:
Note that this will just be looking for a collection called MenuThings in the viewmodel a treeviewitem is bound to.
And I have a hierarchicaldatatemplate for family:
Note that this template references the contextmenu resource.
This gets round some of that placementtarget stuff.
My contextmenu doesn't have any commands of course but it does display.
If some of the treeviewitems won't have commands then you'll get a sort of empty little box. You'd probably want to suppress that. But maybe every one of your treeviewitems will have commands.
My data setup.