0

How do you insert a child node in a TreeView Control in WPF C#?

I have a TreeView control that I have created in XAML in a WPF program using C#.

After adding a couple nodes at the root level, I have written code that loops through the tree structure like so:

        ItemCollection items = treeView1.Items;
        foreach (TreeViewItem n in items)
        {
          ...
        }

Once I find the place in this loop where I want to include a child node, how do I go about inserting a child?

Edited by Reverend Jim: Fixed formatting

2
Contributors
1
Reply
3
Views
7 Years
Discussion Span
Last Post by __avd
0

Have a look at,

xaml markup

<Grid>
        <ListView>
            <TreeView Name="tree1">
                <TreeViewItem Header="One">
                </TreeViewItem>
                <TreeViewItem Header="Two">
                </TreeViewItem>
            </TreeView>
        </ListView>
    </Grid>

code

Dictionary<string, List<string>> items = new Dictionary<string, List<string>>()
            {
                {"One",new List<string>() {"A","B","C"}},
                {"Two",new List<string>() {"P","Q"}},
            };

            
            foreach (TreeViewItem tv in tree1.Items)
            {
                foreach (string item in items[tv.Header.ToString()])
                    tv.Items.Add(item);
            }
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.