我有一个带有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);
如果我将树绑定到树视图,一切都很好,但当我想从树中获取元素时,我有一个问题。例如,我试图从树获得一个特殊的主题,它没有工作。我用下面的代码试了试:
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;
}
但是对于递归,它不起作用。
这就是你想要做的吗?
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;
}