how to insert a child item in a treeview C# WPF

后端 未结 3 743
小蘑菇
小蘑菇 2020-12-22 00:43

I want to add a child item in a TreeViewItem that was added previously. The problem with code like this:

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

3条回答
  •  一生所求
    2020-12-22 01:05

    You are getting String because that is what the source of the TreeView must have been bound to.

    Using this method allows you to iterate over the items and retrieve the TreeViewItem containers that they are inside:

     List GetChildren(TreeViewItem parent)
        {
          List children = new List();
    
          if (parent != null)
          {
            foreach (var item in parent.Items)
            {
              TreeViewItem child = item as TreeViewItem;
    
              if (child == null)
              {
                child = parent.ItemContainerGenerator.ContainerFromItem(child) as TreeViewItem;
              }
    
              children.Add(child);
            }
          }
    
          return children;
        }
    

    Please notice that they check if the TreeViewItem is null after casting it. This is good practice as it prevents the null reference exception from crashing your application if something does happen to go wrong.

    source: https://social.msdn.microsoft.com/Forums/vstudio/en-US/595f0c84-01e7-4534-b73b-704b41713fd5/traversing-the-children-of-a-treeviewitem

提交回复
热议问题