8

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.

9
  • Actually that's exactly how you do it in WPF if you're not using Binding... Commented Jun 27, 2012 at 2:08
  • @Tim in that case you can add only one item, if you try to add child(ren) to the item selectedItem will return null. Commented Jun 27, 2012 at 17:58
  • 2
    What? You're right you can't do it in one call (there's no AddRange(...) function on ItemCollection), but you can just add more. var item = new TreeViewItem(); myTreeView.Items.Add(item); var subItem1 = new TreeViewItem(); var subItem2 = new TreeViewItem(); item.Items.Add(subItem1); item.Items.Add(subItem2); Or do it as part of a loop. I don't see what the problem is. Commented Jun 27, 2012 at 21:24
  • @Tim thanks it works but how do you assign data/value to each node? can give me some direction here? Commented Jun 28, 2012 at 16:39
  • 1
    Right!!!!!! I cannot believe I missed that. Thank you so much you save me lots of time. I CONSIDER THIS AS SOLUTION TO THIS QUESTION. Thank you Tim Commented Jun 28, 2012 at 16:52

4 Answers 4

13

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.

Sign up to request clarification or add additional context in comments.

2 Comments

While this is technically the answer to the posed question (hence +1 from me) it's the suggestion of using HierarchicalDataTemplates, and adhering to solid MVVM that will help the OP the most.
And if you want to add an item at a certain place in the order?
7

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.

3 Comments

first example I had found it but hoping for a shorter path to make it work but seems there is no short cut. 2nd example is what I have done and won't be helpful and even its code is wrong (try zip file delete will NOT work and doesn't tell you have to add children to a node I already have added parent ... I was looking for adding children nodes) so I will go with the first one to spend time and learn it. anyway kind of wondering how people give negative to my question but they have not been answered it. thanks EtherDragon
OK, I went over the first sample and got some ideas about MVVM but honestly yet I don't know how to start writing a simple program using it. Can somebody give me some help here? I can see the separation of view from data and etc but yet don't know how to start and even associate these things together. Any advice will be appreciated.
Getting started witn WPF / MVVM - codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial and codeproject.com/Articles/81484/… If you are getting going on WPF, MVVM really is the only game in town - WPF was built on the concepts of MVC, and MVVM is the WPF specific implimentation of MVC
2

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);

1 Comment

It throughs an exception for ---> tree object to be null. any idea ?
1

Create your model like this

public class WrappedNode
{
    public string Name { get; set; }
    public ObservableCollection<WrappedNode> Nodes { get; set; }

    public WrappedNode()
    {
        Nodes = new ObservableCollection<WrappedNode>();
    }        
}

Node list you want to bind to treeview

private ObservableCollection<WrappedNode> _nodeList;
public ObservableCollection<WrappedNode> NodeList
{
    get { return _nodeList; }
    set
    {
        _nodeList = value;
        RaisePropertyChanged(() => NodeList);
    }
}

And in xaml:

    <TreeView Grid.Row="1"
              ItemsSource="{Binding NodeList}">
        <TreeView.Resources>
            <HierarchicalDataTemplate DataType="{x:Type scnvm:WrappedNode}" ItemsSource="{Binding Nodes}">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Name}" />
                </StackPanel>
            </HierarchicalDataTemplate>
        </TreeView.Resources>
    </TreeView>

If you want a node have children, just add child node to Nodes property of that node

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.