Populate a TreeView from a generic list

Hi All,

I have a list of Categories which I need to bind to a TreeView control in WPF and I can’t find a working tutorial or get it working.

My Category class consist of (ID, Title, ParentID). If the Category is a top level category the parentID is null.

Can anyone sow me how to bind this to a treeview?



Thanks for posting Serenarules but I don’t see how this would help me bind to the xaml.

I can easily use linq to workout top level items but I need to know how I go about binding this to the front end.

Any ideas?

Well, you will probably (and take this with a grain of salt as I know little about xaml) have to reformat your flat list into a parent-child object tree first, which is what I thought you were asking: how to format the list so it could be bound. If I am incorrect, or my post doesn’t help, just wait. Somebody more versed in xaml should be along shortly.


Here’s the code I use to build an indented forum select list. It should be enough to get you going. Now, my methods use an already nested list where each element in the top row has a parentId of null, and each contains a list of it’s own children. Nevertheless, you should be able to augment this to your needs.

public IEnumerable<SelectListItem> BuildForumSelectList(IEnumerable<Forum> entities)
    IList<SelectListItem> list = new List<SelectListItem>();
    GetForumSelectListItems(list, entities, 0);
    return list;
private void GetForumSelectListItems(IList<SelectListItem> list, IEnumerable<Forum> entities, int level)
    foreach (Forum entity in entities.OrderBy(x => x.Sequence))
        GetForumSelectListItem(list, entity, level);
private void GetForumSelectListItem(IList<SelectListItem> list, Forum entity, int level)
    SelectListItem item = new SelectListItem
        Text = string.Format("{0} {1}", new string('-', level * 2), entity.Title).Trim(),
        Value = entity.Id.ToString()
    GetForumSelectListItems(list, entity.Forums, level + 1);