Over a million developers have joined DZone.

Dynamic contextmenu for WPF treeviews

· Big Data Zone

Learn how you can maximize big data in the cloud with Apache Hadoop. Download this eBook now. Brought to you in partnership with Hortonworks.

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.

Hortonworks DataFlow is an integrated platform that makes data ingestion fast, easy, and secure. Download the white paper now.  Brought to you in partnership with Hortonworks


Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

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 }}