2008-12-16 40 views
13

我在看這個控件,它似乎缺乏數據綁定的標準.net「datasource」和「datamember」屬性。這個控件不可綁定嗎?我可以編寫一些自定義函數來填充給定數據源的樹視圖,我想,並且根據需要嵌入數據對象,但這是'最佳實踐'嗎?還是每個人都只是使用第三方樹視圖控件?如何綁定到System.Windows.Forms.Treeview控件?

回答

8

你是正確的,沒有數據綁定。原因是TreeView是分層數據結構。那就是,不是一個清單。結果數據綁定選項對於說明一個List結構是無效的。

可悲的是它創建自己的填入方法或購買第三方控件(最終都會有自己填入方法。)

這裏有Binding Hierarchical Data一個體面的MSDN文章。

2

如果只有幾個級別,我喜歡用一些表填充一個數據集並在列上設置一個DataRelation。然後你使用一些嵌套循環並創建你的樹節點。

5

我使用Developer's Express的樹形控件。它將採取一張數據表並以分層方式顯示/編輯它。它需要的只是表中的一個主鍵字段和一個父id字段,它可以確定哪裏去了哪裏。

如果您推出自己的代碼並使用自己的類,則可以做同樣的事情。

class Node 
    { 
    System.Collections.Generic.List<Node> _Children; 
    String Description; 

    void Node() 
    { 
     _Children = new System.Collections.Generic.List<Node>(); 
    } 

    public System.Collections.Generic.List<Node> Children() 
    { 
     return (_Children); 
    } 
    } 

    class Program 
    { 
    static void Main(string[] args) 
    { 
     System.Collections.Generic.List<Node> myTree = new System.Collections.Generic.List<Node>(); 
     Node firstNode = new Node(); 
     Node childNode = new Node(); 
     firstNode.Children().Add(childNode); 
    } 
    }