As I always seems to forget the simple recursive constructs, I’ve decided to do a short how-to for that problem.
When ever a treeview is to be populated with a dynamic structure, recursive calls come into play. I’m after this structure:
First of all – I’ve this data source:
public class Foo
{
public Foo()
{
Children = new Collection<Foo>();
}
public string Name { get; set; }
public int Id { get; set; }
public Collection<Foo> Children { get; set; }
}
And this collection of ‘Foos’:
Collection<Foo> GenerateFooList()This is not important however; it is just a collection with items. Now – the important thing is the population of the treeview seen above. The population is made in code as seen here:
{
var col = new Collection<Foo>();
var f1 = new Foo() { Id = 0, Name = "A" };
var f2 = new Foo() { Id = 1, Name = "B" };
var f3 = new Foo() { Id = 2, Name = "E" };
var f4 = new Foo() { Id = 3, Name = "F" };
var f5 = new Foo() { Id = 4, Name = "G" };
var f6 = new Foo() { Id = 5, Name = "C" };
var f7 = new Foo() { Id = 6, Name = "D" };
//children
f1.Children.Add(f2);
f1.Children.Add(f3);
f2.Children.Add(f6);
f6.Children.Add(f7);
col.Add(f1);
col.Add(f4);
col.Add(f5);
return col;
}
void FillTree()
{
//get data
Collection<Foo> data = new DataService().FooList;
//clear and add root
tvView.Items.Clear();
TreeViewItem root = new TreeViewItem();
root.Header = "Root";
tvView.Items.Add(root);
AddToTreeview(root, data);
}
void AddToTreeview(TreeViewItem root, Collection<Foo> data)
{
foreach (var foo in data)
{
TreeViewItem itm = new TreeViewItem();
itm.Header = foo.Name;
root.Items.Add(itm);
if (foo.Children.Count > 0) //if needed - call self.
AddToTreeview(itm, foo.Children);
}
}