Dynamic ContextMenu in TreeView and MVVM

I have a ViewModels tree displayed as a TreeView (using HierarchicalDataTemplate). Each instance of the ViewModel has different commands that can be executed on it, which again appear as a list of ViewModels commands for each ViewModel. How can I create a single ContextMenu that opens in a TreeViewItem that has been correctly selected and that populates its commands from the ViewModel list in the ViewModel list? Everything is in decent MVVM mod ...

+6
wpf mvvm contextmenu treeview
source share
1 answer

I think I understand your question. I think you can structure your ViewModels as follows:

interface ICommandViewModel : ICommand { string Name {get;} } interface INodeViewModel { IEnumerable<ICommandViewModel> CommandList {get;} } public class NodeViewModel : INodeViewModel { public NodeViewModel() { //Init commandList //Populate commandList here(you could also do lazy loading) } public NodeViewModel(IEnumerable<ICommandViewModel> commands) { CommandList = commands; } public IEnumerable<ICommandViewModel> CommandList {get;private set;} } 

and then in xaml

 <TreeViewItem> <TreeViewItem.ContextMenu Items={Binding CommandList}> <ContextMenu.ItemTemplate> <DataTemplate> <MenuItem Header="{Binding Name}" Command="{Binding}"/> </DataTemplate> </ContextMenu.ItemTemplate> </TreeViewItem.ContextMenu> </TreeViewItem> 

I do not have much experience working with a hierarchical data template, but you get the gist of the above. You can also do this with style, but I don't have the xaml editor in front of me to give you the correct syntax.

Hope that helps

+3
source share

All Articles