Category / Section
How to configure the expand or collapse behavior in same level of WinForms TreeNavigator?
1 min read
Configure the expand or collapse behavior
In WinForms TreeNavigator, there is no direct option to expand and collapse TreeMenuItem in the same level and it can be achieved by following below steps.
1. Need to create a custom TreeMenuItem class inherited from TreeMenuItem.
2. Implement properties to hold parent – child relation and collection.
3. Then implement the MouseDown event to expand or collapes the child TreeMenuItem collection, when clicking on Parent TreeMenuItem.
C#
public class TreeMenuItemAdv : TreeMenuItem { public TreeMenuItemAdv() { } private List<TreeMenuItemAdv> m_ChildCollection; public List<TreeMenuItemAdv> ChildCollection { get { if(m_ChildCollection == null) { m_ChildCollection = new List<TreeMenuItemAdv>(); } return m_ChildCollection; } } /// <summary> /// Invoked when the mouse down /// </summary> protected override void OnMouseDown(MouseEventArgs e) { if(!this.Collapsed && this.ParentControl != null) { for (int i = 0; i < this.ChildCollection.Count; i++) { TreeMenuItemAdv item = this.ChildCollection[i] as TreeMenuItemAdv; if(item != null) { item.Visible = false; if(this.ParentControl != null) this.ParentControl.SerializeScrollPosition(); this.Collapsed = true; item.Invalidate(); } } } else if(this.Collapsed && this.ParentControl != null) { for(int i = 0; i < this.ChildCollection.Count; i++) { TreeMenuItemAdv item = this.ChildCollection[i] as TreeMenuItemAdv; if(item != null) { item.Visible = true; if(this.ParentControl != null) this.ParentControl.SerializeScrollPosition(); this.Collapsed = false; item.Invalidate(); } } } if(this.ParentControl != null) { this.ParentControl.UpdateVisibleItemBounds(); this.ParentControl.ApplySavedScrollPosition(); } base.OnMouseDown(e); } }
Screenshot:
Samples: