我在左侧创建了一个目录和文件浏览器 TreeView。我希望用户能够浏览树并检查他们想要移动到另一个树视图的文件和目录。
另一个 TreeView 是我在网上找到的一个名为 TreeViewColumn 的用户控件。我将使用该控件来允许用户将其他数据(类别、属性)添加到选定的文件和文件夹中。
我遇到的麻烦是双重的,我需要递归地添加所有孩子(我可以弄清楚),但我需要将未经检查的父母添加到已检查的孩子(以保留层次结构)。
private void IterateTreeNodes(TreeNode originalNode, TreeNode rootNode)
{
//Take the node passed through and loop through all children
foreach (TreeNode childNode in originalNode.Nodes)
{
// Create a new instance of the node, will need to add it to the recursion as a root item
// AND if checked it needs to get added to the new TreeView.
TreeNode newNode = new TreeNode(childNode.Text);
newNode.Tag = childNode.Tag;
newNode.Name = childNode.Name;
newNode.Checked = childNode.Checked;
if (childNode.Checked)
{
// Now we know this is checked, but what if the parent of this item was NOT checked.
//We need to head back up the tree to find the first parent that exists in the tree and add the hierarchy.
if (tvSelectedItems.TreeView.Nodes.ContainsKey(rootNode.Name)) // Means the parent exist?
{
tvSelectedItems.TreeView.SelectedNode = rootNode;
tvSelectedItems.TreeView.SelectedNode.Nodes.Add(newNode);
}
else
{
AddParents(childNode);
// Find the parent(s) and add them to the tree with their CheckState matching the original node's state
// When all parents have been added, add the current item.
}
}
IterateTreeNodes(childNode, newNode);
}
}
private TreeNode AddParents(TreeNode node)
{
if (node.Parent != null)
{
//tvDirectory.Nodes.Find(node.Name, false);
}
return null;
}
任何人都可以帮助使用此代码,以便它递归地添加检查节点(及其父节点,无论检查状态如何)。我需要维护目录层次结构。
谢谢你的帮助!