Easy object binding to Treeview Node

前端 未结 4 1087
北恋
北恋 2021-01-11 14:25

How can I bind an object to a treeview (Winforms) node in C#?

I thought of something like ExNode : Windows.Forms.Node that can take an object as member besides the t

相关标签:
4条回答
  • 2021-01-11 14:48

    This MSDN article has some good information, for example:

    class myTreeNode : TreeNode
    {
       public string FilePath;
    
       public myTreeNode(string fp)
       {
          FilePath = fp;
          this.Text = fp.Substring(fp.LastIndexOf("\\"));
       }
    }
    
    0 讨论(0)
  • 2021-01-11 14:50

    You might look into the TreeListView. It isn't perfect, but it works very well and makes the process of displaying objects in a tree view much easier than any other way I have found.

    0 讨论(0)
  • 2021-01-11 14:51

    imho you have several strategies :

    1. stick an object of any type in the Tag property of any Node : downside : you'll have to cast it back to its 'native form' when you retrieve it to use it : if that "native form" is anything but type 'Object.

    2. sub-class TreeNode, and add a public fields, Public Properties, or whatever, for your objects ... or even List ... ... or whatever you need to associate with the Node.

    3. assuming your objects are of the same type, you could create a dictionary of type : Dictionary <TreeNode, myObjectType>, instantiate it, and, as needed, store a TreeNode and its associated Object(s) that way as a Key/Value Pair.

    Strategies #1, and #3 have the advantage that you can store an associated object ONLY as needed Strategy #2 : is more suited to the case where you anticipate every TreeNode is going to have an associated object(s).

    Of course with stragies #1 and #3, you will need to test at run-time for the presence or absence of an object associated with a particular Node.

    Strategy #1's an easy test : if the Tag propety of the Node is Null : you know there's no object : if not null ... and there may be more than one type of object stored in the Tag field ... then you'll have to pull out the Tag object, and make sure it's the right type as in : (the example that follows assumes a public class, "Class1," has been assigned to tag of the first node in the TreeView :

    TreeNode thisNode = theTreeView.Nodes[0];
    if (((thisNode.Tag != null) && (thisNode.Tag is Class1))) ... handle the object ...
    

    Strategy #3 is a little easier since you can just evaluate if the Dictionary<Node, myObject>.Contains the Node as a Key.

    0 讨论(0)
  • 2021-01-11 14:52

    Are you looking for something like the Tag property on TreeNodes? It can hold any object.

    http://msdn.microsoft.com/en-us/library/system.windows.forms.treenode.tag.aspx

    0 讨论(0)
提交回复
热议问题