开发者

Avoid expansion of certain TreeNode nodes upon TreeNode.ExpandAll?

开发者 https://www.devze.com 2023-03-22 02:14 出处:网络
Nobody asked that before: What is an efficient way to avoid the expansion of certain TreeNode class descendants in a WinForms TreeView when the user does the \"Expand all\" thing, but still let him e

Nobody asked that before:

What is an efficient way to avoid the expansion of certain TreeNode class descendants in a WinForms TreeView when the user does the "Expand all" thing, but still let him expand such nodes by clicking on the + symbol?

Sure I can handle BeforeExpand, but I have a hard time setting e.Cancel to true only if it is an ExpandAll operation. I wonder how I can determine this? I could subclass TreeView and override Expan开发者_开发百科dAll -- but that one cannot be overriden...


Seems like standard .NET treeview doesn`t have the way other than you described: trigger flag before ExpandAll, handle BeforeExpand and enable e.Cancel for appropriate nodes when flag is enabled.

As the ExpandAll method isn`t virtual you have these ways to follow:

  • Inherit from the TreeView class and add ExpandAllEx method where trigger this flag. No a good one because you need to cast to your tree class everywhere you use the tree instance.
  • Add an extension method for the TreeView class where use tree.Tag property for this flag. More useful way with minimal changes in existing code.


This works 100%. I think. Sigh.

  Private Sub MyTreeViewExpandNodes(ByVal Nodes As TreeNodeCollection)
    For Each Node As TreeNode In Nodes
      If Not (TypeOf Node Is SpecialTreeNode) Then
        Node.Expand()
        MyTreeViewExpandNodes(Node.Nodes)
      End If
    Next
  End Sub

  Private Sub MyTreeView_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyTreeView.KeyDown
    If e.KeyCode = Keys.Multiply Then
      e.Handled = True
      e.SuppressKeyPress = True
      MyTreeViewExpandNodes(MyTreeView.Nodes)
    End If
  End Sub
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号