Dynamic contextmenu for WPF treeviews
Join the DZone community and get the full member experience.
Join For FreeWhen 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.
Windows Presentation Foundation
Opinions expressed by DZone contributors are their own.
Trending
-
How to Use an Anti-Corruption Layer Pattern for Improved Microservices Communication
-
Performance Comparison — Thread Pool vs. Virtual Threads (Project Loom) In Spring Boot Applications
-
An Overview of Cloud Cryptography
-
Opportunities for Growth: Continuous Delivery and Continuous Deployment for Testers
Comments