Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Dynamic contextmenu for WPF treeviews

DZone's Guide to

Dynamic contextmenu for WPF treeviews

· Big Data Zone ·
Free Resource

How to Simplify Apache Kafka. Get eBook.

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.

12 Best Practices for Modern Data Ingestion. Download White Paper.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}