Tsukasa
Tsukasa

Reputation: 6552

Add child nodes to treeview without using foreach

WPF treeview. Is there a way to add a child node to an already populated treeview without having to run in a for/foreach to check the header then converting that into an TreeViewIem ?

private void AddChildNode(string _rootNode, string _childeNode)
    {
        foreach (TreeViewItem node in tvSQLTasks.Items)
        {
            if (node.Header.Equals(_rootNode))
            {
                node.Items.Add(new TreeViewItem() { Header = _childeNode });
            }
        }
    }

Upvotes: 0

Views: 186

Answers (1)

Dean Kuga
Dean Kuga

Reputation: 12119

Create an ObservableCollection collection of objects, populate the collection with objects representing what treeview is supposed to display and bind that collection to ItemSource property of your TV.

Binding is the only proper way to go about populating your treeview with items in WPF and if you use the ObservableCollection you'll have the added benefit of items added to/removed from the collection "automagically" appearing in/disappearing from your TV without writing any additional code.

Depending on how complex your treeview needs to be you might have to use HierarchicalDataTemplate and ItemStyleSelector.

Upvotes: 1

Related Questions