In winformProgramIn, we sometimes use the Treeview control as the navigation bar of the system (Figure 1). These treenode items are usually dynamically generated based on user permissions, in this case, how can we better handle the treenode click event? (Click, DoubleClick, etc)
Figure 1
In treenode, there is a tag attribute with the type of object. Usually I will skillfully use this tag to process the above click events. BecauseCodeCode 1 defines the navnode class and the click () and DoubleClick () methods; code 2 demonstrates how to instantiate treenode and handle the treenode click event;
Class Navnode { Public Virtual Void Click (){} Public Virtual Void DoubleClick (){}} Class Emptynode: navnode {} // Function 1 Class Fun1node: navnode { Public Override Void DoubleClick (){ Try {Indexform =New Indexform (); indexform. Show ();} Catch (Exception ex) {MessageBox. Show (ex. Message );}}}
Code 1
// Todo: menu nodes can be dynamically generated based on user permissions. Treenode node = New Treenode ( " Homepage " ); Node. Tag = New Emptynode (); treenode nodefun1 = New Treenode ( "Function 1 " ); Nodefun1.tag = New Fun1node (); node. nodes. Add (nodefun11); treeview1.nodes. Add (node); treeview1.nodemousedoubleclick + = (S, e) => { If (E. Button =System. Windows. Forms. mousebuttons. Left) {navnode currentnode = (Navnode) E. node. Tag; If (Currentnode! = Null ) {Currentnode. DoubleClick ();}}};
Code 2
In addition to common classes, navnode in code 1 can also be defined as an abstract class or interface. If your subclass still needs to inherit some similar permission control base classes, it would be better to define navnode as inavnode. The click and DoubleClick methods in navnode in code 1 can be defined as abstract methods if you do not need to implement them by default. Here I define it as a virtual function because sometimes I need to perform some pop-up dialog box operations on the click and DoubleClick of navnode.