Over a million developers have joined DZone.

Dynamic contextmenu for WPF treeviews

· Big Data Zone

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

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 Sandbox is a personal, portable Apache Hadoop® environment that comes with dozens of interactive Hadoop and it's ecosystem tutorials and the most exciting developments from the latest HDP distribution, brought to you in partnership with Hortonworks.

Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
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.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}