1
例如,有.Name
,.Text
字段。如果我需要Type
,Path
和Direction
字段,如何將它們添加到類TreeNode
?如何將新字段添加到TreeNode對象?
例如,有.Name
,.Text
字段。如果我需要Type
,Path
和Direction
字段,如何將它們添加到類TreeNode
?如何將新字段添加到TreeNode對象?
這是否滿足您的要求?我已經將這些屬性顯示爲屬性,但省略{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,你可以這樣做:如果你想使用的Tag屬性,而不是直接在繼承節點存儲這些的
myTreeNode node = new myTreeNode();
treeview1.Nodes.Add(node);
(顯示只有兩個屬性,而不是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'屬性中存儲對我需要的所有字段的引用。 –
我是否需要構造函數來初始化此代碼中的所有字段? –
如果您閱讀http://msdn.microsoft.com/en-us/library/system.windows.forms.treenode.tag.aspx,您會看到標籤屬性存在以保存節點的其他數據。是的,你需要一個構造函數來初始化它們。你可以讓它們成爲只讀屬性,並只在構造函數中設置它們。但是在某些情況下,您可能希望將它們設置爲TreeNode中的字段,就像您最初詢問的那樣。 –