如何在 WPF 的 TreeView 控件中插入子节点? [英] How to insert a child node in a TreeView Control in WPF?

查看:94
本文介绍了如何在 WPF 的 TreeView 控件中插入子节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在 WPF 程序中用 XAML 创建的 TreeView 控件

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

这篇关于如何在 WPF 的 TreeView 控件中插入子节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆