【问题标题】:How to add new fields to TreeNode object?如何向 TreeNode 对象添加新字段?
【发布时间】:2012-09-12 15:34:22
【问题描述】:

例如,有.Name.Text 字段。如果我需要TypePathDirection 字段怎么办,如何将它们添加到TreeNode 类中?

【问题讨论】:

    标签: c# .net winforms treeview treenode


    【解决方案1】:

    这是否满足您的预期?我已将这些显示为属性,但省略 {get;set;} 并且您将拥有字段。

      class myTreeNode : System.Windows.Forms.TreeNode
      {
        public string NodeType { get; set; }
        public string NodePath { get; set; }
        public string Direction { get; set; }
      }
    

    要将 myTreeNode 实例添加到 TreeView,您可以这样做:

    myTreeNode node = new myTreeNode();  
    treeview1.Nodes.Add(node);
    

    如果您想使用 Tag 属性而不是将这些直接存储在继承的节点中,(仅显示两个属性而不是 3 个)

    class NodeTag
    {  
      public NodeTag(string path, string direction)
      {
         NodePath = path;
         Direction = direction;
      }
      public string Direction {get;set;}
    }
    

    然后,在创建树的代码中,您将执行以下操作:

    TreeNode node = new TreeNode();
    node.Tag = new NodeTag("my path", "South");
    treeView1.Nodes.Add(node);
    

    【讨论】:

    • 什么更好,像你说的那样创建类myTreeNode,或者在TreeView.Tag属性中存储对我需要的所有字段的对象的引用?
    • 我需要构造函数来初始化这段代码中的所有字段吗?
    • 如果您阅读msdn.microsoft.com/en-us/library/…,您会看到标记属性用于保存节点的附加数据。是的,您需要一个构造函数来初始化它们。您可以将它们设为只读属性并仅在构造函数中设置它们。但在某些情况下,您可能希望按照最初的要求将它们设置为 TreeNode 上的字段。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 2015-04-10
    相关资源
    最近更新 更多