Dax
Dax

Reputation: 3

Binding a list of items containing a list of items

I've got my class:

public class Comment
{
    ...
    public List<Comment> Children;
}

In my ViewModel, I've got a ObservableCollection with my Comments, the binding is working but I would like to bind also the Children.

Here is my View:

<ListBox 
    ItemsSource="{Binding Comments}" 
    ItemTemplate="{Binding Source={StaticResource comment}}">
</ListBox>

The template is a UserControl binding for each Comment the content and the children:

<Grid>
    <TextBlock Text="{Binding Body}" />

    <ListBox 
        ItemsSource="{Binding Children}" 
        ItemTemplate="{Binding Source={StaticResource comment}}">
    </ListBox>
</Grid>

Obviously I can't bind Children because I need an ObservableCollection but I can't see how to do it, if I replace in my Comment class the List by an ObservableCollection, it's not working neither.

Right now, I list only my Comments in my list in the ViewModel but I would like to do it recursively for each children.

Thanks

Upvotes: 0

Views: 142

Answers (1)

Uri London
Uri London

Reputation: 10797

How deep is the tree? Does the children comments can have children comments at arbitrary level? In that case, you are looking at a hierarchical data structure, and you use <HierarchicalDataTemplate>. Here is a fairly straight forward sample: http://www.dev102.blogspot.com/2007/12/how-to-use-hierarchical-datatemplate-in.html, or the MSDN article: http://msdn.microsoft.com/en-us/magazine/cc700358.aspx#id0190065.

If this is just a simple two level deep structure, then have two classes Commend and ChildCommend, and your approach will work.

In any case, Comment seems to be a Model class. It would make sense to also have CommentVm, with observable collection of children comments. Create a List to ObservableCollection with the linq extension function Select

Upvotes: 1

Related Questions