Hej hej,
i'm currently working on a c# wpf project where i want to dynamically populate a TreeView from a linear list of Items.
My starting point was this article on codeproject:
https://www.codeproject.com/Articles/26288/Simplifying-the-WPF-TreeView-by-Using-the-ViewMode
John Smith shows how to use the HierarchalDataTemplate withing TreeViews. So far this is working. My problem is to dynamically generate a hierarchical Tree from a linear list of items. I have tried to adapt the solutions found here
Mapping a flat list to a hierarchical list with parent IDs C#
and here
TreeView directories in C# WPF
but somehow i did not succeed.
My item class looks like this:
public class Item
{
public string Name { get; set; }
public ItemPath[] ParentPath { get; set; }
public ItemPath[] Path { get; set; }
}
ItemPath class
public class ItemPath
{
public int Level { get; set; }
public string Name { get; set; }
}
Targeted hierarchial class
public class ItemTree
{
public string Name { get; set; }
public Item Item { get; set; }
public List<ItemTree> ChildTree { get; set; }
}
I am using this flat list to test my methods:
var items = new List<Item>()
{
new Item()
{
Name = "item 0",
Path = new ItemPath[]
{
new ItemPath() { Name = "Red", Level = 1 },
}
},
new Item()
{
Name = "item 1",
Path = new ItemPath[]
{
new ItemPath() { Name = "Red", Level = 1 },
new ItemPath() { Name = "Green", Level = 2 },
}
},
new Item()
{
Name = "item 2",
Path = new ItemPath[]
{
new ItemPath() { Name = "Red", Level = 1 },
new ItemPath() { Name = "Violet", Level = 2 },
}
},
new Item()
{
Name = "item 3",
Path = new ItemPath[]
{
new ItemPath() { Name = "Blue", Level = 1 },
new ItemPath() { Name = "Black", Level = 2 },
}
},
new Item()
{
Name = "item 4",
Path = new ItemPath[]
{
new ItemPath() { Name = "Blue", Level = 1 },
new ItemPath() { Name = "Green", Level = 2 },
}
},
new Item()
{
Name = "item 5",
Path = new ItemPath[]
{
new ItemPath() { Name = "Red", Level = 1 },
new ItemPath() { Name = "Green", Level = 2 },
}
},
};
My goal is to have a hierarchy like this
- [Red]
- item 0
- [Green]
- item 1
- item 5
- [Violet]
- item 2
- [Blue]
- [Black]
- item 2
- [Green]
- item 4
- [Black]
My current attempt is below. It's the rewritten version of the stackoverflow post from above:
// class to create dummy data as described above
var dummyData = new DummyData();
var items = dummyData.CreateTier2DummyList();
var cat = items.Select(r => new ItemTree()
{
Path = r.Path,
Item = r,
// parent path is generated dynamically
ParentPath = r.Path.Reverse().Skip(1).Reverse().ToArray(),
}).ToList();
var lookup = cat.ToLookup(c => c.ParentPath);
foreach (var c in cat)
{
if (lookup.Contains(c.Path))
c.ChildTree = lookup[c.ParentPath].ToList();
}
Somehow i think that using an array as the path and parent path is not a good idea. But it reflects an absolute path (comparable to a file path in a file system).