获取递归observablecollection项

时间:2014-03-12 21:17:31

标签: c# .net wpf recursion observablecollection

我有一个带有observablecollection的TreeITem类。

/// <summary>
/// Item class to generate a tree view of the queues and topics from the service bus.
/// </summary>
public class TreeItem
{
    /// <summary>
    /// The whole namespace tree
    /// </summary>
    public static ObservableCollection<TreeItem> Tree { get; set; }

    //TreeItem properties
    public string Name { get; set; }
    public ObservableCollection<TreeItem> Items { get; set; }
    .........

如果我创建树结构,我会执行以下操作:

            //Get queues and topics
            TreeItem namespaceTree = new TreeItem() { Name = namespaceManager.Address.ToString() };
            TreeItem queuesTree = GetQueues(namespaceManager.GetQueues());

            //Get queues and topics
            TreeItem namespaceTree = new TreeItem() { Name = namespaceManager.Address.ToString() };
            TreeItem queuesTree = GetQueues(namespaceManager.GetQueues());
            TreeItem topicsTree = GetTopics(namespaceManager.GetTopics());         

            //Generate the topic structure.
            namespaceTree.Items.Add(queuesTree);
            namespaceTree.Items.Add(topicsTree);
            Tree.Add(namespaceTree);

如果我将树绑定到树视图,则everthing工作正常,但是当我想从树中获取元素时,我遇到了问题。例如,我试图从树中获得一个特殊主题但它没有用。我用以下代码尝试了它:

    private TreeItem GetTopicFromTree(ObservableCollection<TreeItem> tree)
    {
        TreeItem treeItem = null;
        foreach(var item in tree)
        {
            if (!item.Name.Equals("topicx"))
                GetTopicFromTree(item.Items);

            else
                treeItem = item;
        }

        return treeItem;
    }

但随着递归,它没有奏效。有人知道如何做到这一点吗?

祝你好运

1 个答案:

答案 0 :(得分:0)

这是你想要做的吗?

private TreeItem GetTopicFromTree(ObservableCollection<TreeItem> tree)
{
    foreach(var item in tree.Items)
    {
        var found = GetTopicFromTree(item);

        if (found != null)
            return found;
    }

    return null;
}

但TreeItem不是ObservableCollection,因此您需要GetTopicFromTree的第二种方法来处理TreeItem

private TreeItem GetTopicFromTree(TreeItem tree)
{
    if (Name.Equals("topicx"))
        return this;

    foreach(var item in tree.Items)
    {
        var found = GetTopicFromTree(item);

        if (found != null)
            return found;
    }

    return null;
}

或者,也许是一个触摸清洁器

private TreeItem FindTopic(TreeItem node, string name)
{
    if (node.Name == name)
        return node;

    foreach (var child in node.Items)
    {
        var found = FindTopic(child, name);
        if (found != null)
            return found;
    }

    return null;
}