how do i create a hierarchical structure in WPF using treeview?
2 Answers
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;
}
}
5 Comments
BigBug
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
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.
Fischermaen
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.BigBug
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
Got it... it should have been "theParent = (TreeViewItem)Parent;" Thanks so much for your help!
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.