In Visual C++/MFC we used to add a node to a tree and then by referencing the node we could add children under parent node. However, in WPF there is no such a thing as I see. I'm confused how I can add child/children to a node?
any help will be appreciated.
it seems 2 people know MVVM already!
Solution is given by Tim below.
Since the OP said my comment was really what he considered an answer, I figured I'd go ahead and turn it into an answer.
What is described in the question is exactly how you could do it in WPF. For instance:
var item = new TreeViewItem();
myTreeView.Items.Add(item);
var subItem1 = new TreeViewItem();
var subItem2 = new TreeViewItem();
item.Items.Add(subItem1);
item.Items.Add(subItem2);
That'll add a bunch of blank items.
You can use the Header property of each TreeViewItem to control what is displayed and use the Tag property to hold data, if you want to go that route.
It would likely be preferable, however, to go the binding route and use HierarchicalDataTemplates to control the look. That way you're not manually creating these fake containers (the TreeViewItems) for your data.
I'd suggest reading up on HierarchicalDataTemplates, as that'll give you a decent overview of how the process should work with bindings. Also just read up on MVVM in general.
A quick google search "wpf treeview" found several great articles on how to correctly use treeviews in WPF.
Example 1: http://www.codeproject.com/Articles/26288/Simplifying-the-WPF-TreeView-by-Using-the-ViewMode
Example 2: http://www.c-sharpcorner.com/uploadfile/mahesh/treeview-in-wpf/
That should get you started - update your question when you have tried the MVVM approach and have more specific questions.
To add an item as parent:
var item = new TreeViewItem();
item.Header = "First Element";
tree.Items.Add(item); //tree is your treeview
To add an element as a child of a specific element :
var subItem = new TreeViewItem();
subItem.Header = "Subitem";
var parent = tree.SelectedItem as TreeViewItem; // Checking for selected element
parent.Items.Add(subItem);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With