0

how do i create a hierarchical structure in WPF using treeview?

BigBug
  • 6,202
  • 23
  • 87
  • 138

2 Answers2

1

Here is my suggestion:

//create treeNode myParent = null;  
while (Reader.Read()) 
{ 
    switch (reader.NodeType) 
    { 
        case XmlNodeType.Element: // The node is an element. 
            var newNode = new TreeViewItem 
            { 
                Header = reader.Name 
            }; 

            if(theParent !=null) 
            { 
                theParent.Items.Add(newnode);  
            } 
            else 
            { 
                treeView.Items.Add(newnode);  
            } 
            theParent = newnode; 
            break; 

        case XmlNodeType.Text: //Display the text in each element. 
            Console.WriteLine(reader.Value); 
            break; 

        case XmlNodeType.EndElement: //Display the end of the element. 
            Console.Write("</" + reader.Name); 
            Console.WriteLine(">"); 
            if (theParent != null)
            {
                theParent = theParent.Parent;
            } 
            break; 
     } 
 } 
Fischermaen
  • 12,238
  • 2
  • 39
  • 56
  • hmm, i had tried this but the problem comes in with "Nodes.Add" Error 1 'System.Windows.Controls.TreeViewItem' does not contain a definition for 'Nodes' and no extension method 'Nodes' accepting a first argument of type 'System.Windows.Controls.TreeViewItem' could be found (are you missing a using directive or an assembly reference?) – BigBug Nov 21 '11 at 20:20
  • for some reason, doesn't work =/ The treeView is completely empty when i run this program. i've updated the code in my question so you can see exactly what i'm doing. – BigBug Nov 21 '11 at 20:57
  • 1
    The second line in your sample ` var theParent = new TreeViewItem {};` is the reason for that behavior, change it to `TreeViewItem theParent = null;` and it should work. – Fischermaen Nov 21 '11 at 21:02
  • Hmm there is still an issue with parent. When i run the program now i get this: UnvalidCastException was unhandled: Unable to cast object of type 'System.Windows.Controls.TreeView' to type 'System.Windows.Controls.TreeViewItem'. If i don't cast then i get the "Cannot implicityly convert type 'System.Windows.DependecyObject' to 'System.Windows.Controls.TreeViewItem'. – BigBug Nov 21 '11 at 21:05
  • Got it... it should have been "theParent = (TreeViewItem)Parent;" Thanks so much for your help! – BigBug Nov 21 '11 at 21:07
0

Don't try to manipulate the WPF TreeView directly. Instead, make your own "view model" representing a node, then bind it recursively to the TreeView using HierarchicalDataTemplate.

More info here.

Branko Dimitrijevic
  • 50,809
  • 10
  • 93
  • 167