所以...我做了一些我通常不做的事情,并复制/粘贴了这个功能;这完全符合我的需要。我没有原始资料,可能是6个月前。好消息是它运作良好。坏消息是我不太了解它并希望进行修改。
此函数获取一个看起来像“root \ subcat1 \ subcat2 \ subcat3”的字符串列表,将其吐入字符串数组,然后输出到分层树视图(在WPF中显示)。
我想在每个级别按字母顺序排列树。我看到一个空的TreeObject(父)被添加到iTreeSource ...并且正在返回iTreeSource,但是在循环中没有对它进行修改。为什么不,如何将完成的TreeObject添加到iTreeSource ...以及如何按字母顺序排列?此外,欢迎任何改进。
private ObservableCollection<TreeObject> TreeLoad(List<string> sortedPath)
{
ObservableCollection<TreeObject> iTreeSource = new ObservableCollection<TreeObject>();
TreeObject parent = new TreeObject();
string pathConstructor = "error";
iTreeSource.Add(parent);
foreach (string arrayPath in sortedPath)
{
string[] individualPath = arrayPath.Split('\\');
if (individualPath.Length > 0)
{
pathConstructor = individualPath[0];
parent.Name = individualPath[0];
}
parent.Path = pathConstructor;
TreeObject tempGroup = parent;
if (individualPath.Length > 1)
{
for (int i = 0; i < individualPath.Length; i++)
{
if (tempGroup.Children.Count != 0)
{
foreach (TreeObject matchinGrp in tempGroup.Children)
{
if (matchinGrp.Path == pathConstructor)
{
tempGroup = matchinGrp;
break;
}
}
if (tempGroup.Path != pathConstructor)
{
TreeObject child = new TreeObject();
child.Name = individualPath[i];
child.Path = pathConstructor;
child.Parent = tempGroup;
tempGroup.Children.Add(child);
tempGroup = child;
}
}
else
{
if (tempGroup.Path != pathConstructor)
{
TreeObject child = new TreeObject();
child.Name = individualPath[i];
child.Path = pathConstructor;
child.Parent = tempGroup;
tempGroup.Children.Add(child);
tempGroup = child;
}
}
if (i != individualPath.Length - 1 && individualPath.Length > 1)
{
pathConstructor = string.Format("{0}\\{1}", pathConstructor, individualPath[i + 1]);
}
}
}
}
return iTreeSource;
}