0

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

2 Answers 2

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; 
     } 
 } 
Sign up to request clarification or add additional context in comments.

5 Comments

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?)
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.
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.
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'.
Got it... it should have been "theParent = (TreeViewItem)Parent;" Thanks so much for your help!
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.