Over a million developers have joined DZone.

Dynamic contextmenu for WPF treeviews

DZone's Guide to

Dynamic contextmenu for WPF treeviews

· Big Data Zone
Free Resource

Need to build an application around your data? Learn more about dataflow programming for rapid development and greater creativity. 

When building a treeview into an application I built for one of my clients, I happened upon a strange phenomenon: when applying a contextmenu to a treenode, the childtreenodes get that same menu as well. In the case of this application, this turned out to be unwanted behaviour. How to solve this? Well solving this turned out to be easy in the end.  First of all, I subclassed the TreeViewItem like this:
 public class MyTreeViewItem:TreeViewItem  
     public bool ShowMenu { get; set; }  
     public MyTreeViewItem()  
       : base()  
       ShowMenu = false;  
Then in the main program I had the following code (documentView is the TreeView)
 void documentView_ContextMenuOpening(object sender, ContextMenuEventArgs e)  
       var selectedItem = documentView.SelectedItem as MyTreeViewItem;  
       if (selectedItem != null)  
         if (!selectedItem.ShowMenu)  
           e.Handled = true;  
What you do is, when you add an item to the treeview, instead of a standard treeViewItem you add a MyViewItem with showmenu either set to true or false. This way, when the menu is trying to open, you can determine whether to show the menu or not. Mind you, this only works if you build the treeview programmatically.

Check out the Exaptive data application Studio. Technology agnostic. No glue code. Use what you know and rely on the community for what you don't. Try the community version.


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}