开发者

How to insert a child node in a TreeView Control in WPF?

开发者 https://www.devze.com 2022-12-30 22:22 出处:网络
I have a TreeView control that I have created in XAML in a WPF program After adding a couple nodes at the root level, I have written code that loops through the tree structure like so:

I have a TreeView control that I have created in XAML in a WPF program

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?


This is a piece of very naive code that does it, you might want to make it more defensive if you actually use it.

var items = treeView1.Items;
var item = new TreeViewItem() { Header = "Interesting" };
items.Add(item);
var subitem = new TreeViewItem() {Header = "Sub Item"};
foreach (TreeViewItem n in items)
{
  if (n.Header == "Interesting")
    (n as TreeViewItem).Items.Add(subitem);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号