c# - 如何避免 TreeView 中的重复值?

标签 c# wpf

我正在寻找一种强大而简单的方法来避免 TreeView 中的重复值,现在我以这种方式执行插入:

while (rdr.Read())
{
     checkExists(rdr.GetString(3));
     rootNode.Items.Add(new TreeViewItem() { Header = rdr.GetString(3) });
}

其中 RDR 是一个包含所有要递归添加的值的播放器。现在,如果已经添加了这些值,我会得到重复的值,所以我创建了一个函数 checkExists,您应该检查该值是否已经在 TreeView 中。我还没有找到适用于 WPF 的解决方案,我仍在学习如何使用此控件,我会知道如何执行此操作。

public void checkExists(string campionato) 
{
      foreach (TreeView node in nation_team)
      {
           if (NodeExists(node, campionato))
           exists = true;
      }
}

这个方法还没有准备好,它只是一个测试版。

private bool NodeExists(TreeNode node, string key) {
        foreach (TreeNode subNode in node.Nodes) {
            if (subNode.Text == key) {
                return true;
            }
            if (node.Nodes.Count > 0) {
                NodeExists(node, key);
            }
        }
        return false;
    }

我尝试过的可能解决方案,在 foreach 中我试图遍历所有节点,但编译器告诉我有关 GetEnumerator

最佳答案

如果我理解你的问题,你的 NodeExists 函数没有工作。你看,你没有对你的第二个案例做任何事情,这就是为什么给你一个错误。此外,您需要检查 subNode

的子节点

一个合适的解决方案,应该是这样的:

private bool NodeExists(TreeNode node, string key) 
{
    foreach (TreeNode subNode in node.Nodes) 
    {
        if ( subNode.Text.Equals(key) ) 
        {
            return true;
        }

        var nodeChildExists = NodeExists( subNode.Nodes, key );

        if(nodeChildExists)
        {
            return true;
        }
    }

    return false;
}

关于c# - 如何避免 TreeView 中的重复值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32274354/

相关文章:

c# - 随机种子递归函数。我该怎么做?

c# - 使用 Roslyn 向类添加新字段声明

c# - 初学者如何编写 Windows GUI 程序的综合教程

c# - 如何扩展匿名类的对象

c# - Java.Lang.NoClassDefFoundError : Timeout exceeded getting exception details Xamarin Android 错误

c# - 为什么使用 Caliburn Micro Conductor.OneActive 时,Blend Interaction 事件触发器会多次触发?

c# - WPF Mahapps - 如何隐藏汉堡菜单集合中的选项卡?

.net - 有可用的 WPF 备忘单吗?

c# - 为什么我的异常在 wpf 应用程序中没有任何区别?

wpf - 带有 WPF-ListView 的面包屑样式