【问题标题】:Binding a list of items containing a list of items绑定包含项目列表的项目列表
【发布时间】:2012-03-14 10:07:46
【问题描述】:

我上课了:

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

在我的 ViewModel 中,我有一个带有评论的 ObservableCollection,绑定正在工作,但我还想绑定孩子。

这是我的观点:

<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 类中将 List 替换为 ObservableCollection,它也不起作用。

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

谢谢

【问题讨论】:

标签: c# wpf list binding observablecollection


【解决方案1】:

树有多深?子 cmets 是否可以有任意级别的子 cmets?在这种情况下,您正在查看分层数据结构,并使用 。这是一个相当直接的示例: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

如果这只是一个简单的两级深度结构,那么有两个类 Commend 和 ChildCommend,你的方法就行了。

无论如何,Comment 似乎是一个 Model 类。也有 CommentVm 是有意义的,它具有可观察的子 cmets 集合。使用 linq 扩展函数 Select 为 ObservableCollection 创建一个列表

【讨论】:

  • 完美,这就是我想要的!谢谢
猜你喜欢
  • 1970-01-01
  • 2016-07-07
  • 2017-07-30
  • 2023-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多