绑定包含项目列表的项目列表



我有我的类:

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

在我的ViewModel中,我有一个带注释的ObservableCollection,绑定正在工作,但我也想绑定Children。

这是我的看法:

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

模板是每个Comment、内容和子项的UserControl绑定:

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

很明显,我不能绑定Children,因为我需要一个ObservableCollection,但我不知道如何做到这一点,如果我在Comment类中用ObservableCollectionList替换List,它也不起作用。

现在,我只在ViewModel的列表中列出我的评论,但我想为每个孩子递归地列出。

感谢

树有多深?儿童评论是否可以有任意级别的儿童评论?在这种情况下,您将看到一个分层数据结构,并使用<层次结构数据模板>。以下是一个相当直接的示例:http://www.dev102.blogspot.com/2007/12/how-to-use-hierarchical-datatemplate-in.html,或MSDN文章:http://msdn.microsoft.com/en-us/magazine/cc700358.aspx#id0190065.

如果这只是一个简单的两级深层结构,那么就有两个类Comed和ChildComed,你的方法就会奏效。

无论如何,Comment似乎是一个Model类。还可以有CommentVm,可以观察到孩子们的评论。使用linq扩展函数创建一个列表到ObservableCollection Select

最新更新