【问题标题】:C# Windows 10 UWP Nested Listviews with Databinding带有数据绑定的 C# Windows 10 UWP 嵌套列表视图
【发布时间】:2016-06-26 00:43:46
【问题描述】:

我有一个从网站检索 cmets 的应用程序。我可以以编程方式将它们添加到 StackPanel,计算它们的缩进以进行评论回复,但我想了解如何将 cmets 列表绑定到 ListView 并让它在那里正确显示。

我的评论类如下所示:

    class Comment 
    {
        public List<Comment> Replies { get; set; }
        public string Body { get; }
        public int Level { get; set; }

        public Comment(string BodyText) 
        {
            Body = BodyText;
        }

        public Comment(string BodyText, List<Comment> replies, int level) 
        {
            Body = BodyText;
            Replies = replies;
            Level = level;
        }
    }

因此,每个评论都可以有一个列表 cmets(回复),Level 变量表示评论的深度。

设置一个 ListView 的过程是什么,以便我可以将一个 cmets 列表绑定到它并且这些 cmets 回复这些等等?或者有更好的方法吗?

谢谢。

这就是我目前实现它的方式,这在视觉上是正确的,但我想使用数据绑定而不是通过代码来实现。

【问题讨论】:

    标签: c# xaml listview nested uwp


    【解决方案1】:

    创建一个 ListView,将其 ItemsSource 属性绑定到顶级 cmets 列表。在垂直 StackPanel 中使用包含注释的 ItemTemplate 和另一个 ListView。内部 ListView 需要获得与它所在的相同的 ItemTemplate。我不确定 {StaticResource} 是否会处理这个问题,但它应该。

    如果你使用 ObservableCollections 这实际上是动态的。

    【讨论】:

      【解决方案2】:

      我推荐你使用第三方包WinRTXamlToolkit。其中包含一个可以很好地满足您的层次结构要求的 TreeView 控件。您可以将 cmets 集合绑定到后面的 TreeView 控件代码。代码示例如下:

      Xaml 代码

       <controls:TreeView   Width="400"   MaxHeight="400" x:Name="Treeviewcomment">
           <controls:TreeView.ItemTemplate>
               <DataTemplate>
                   <TextBlock Text="{Binding Body}"/>
                   <data:DataTemplateExtensions.Hierarchy>
                       <data:HierarchicalDataTemplate ItemsSource="{Binding Replies}" />
                   </data:DataTemplateExtensions.Hierarchy>
               </DataTemplate>
           </controls:TreeView.ItemTemplate>
       </controls:TreeView>
      

      绑定代码

      this.InitializeComponent();
      ObservableCollection<Comment> comments = new ObservableCollection<Comment>
      {
          new Comment ("By the way,I have noticed that ..."),
          new Comment("Has this been metioned anywhere before..",
          new List<Comment>
          {
              new Comment("Delta upgrade..."),
              new Comment("When only stuff that...",
                  new List<Comment> {
                      new Comment("That's blloby...")},
                  3)},
          2),
          new Comment("Just had to turn off..")
      };
      

      结果:

      uwp 的特殊 nuget 包:WinRT XAML Toolkit。而且我也把上面的code example上传到了GitHub。

      【讨论】:

        猜你喜欢
        • 2017-02-21
        • 2018-08-11
        • 1970-01-01
        • 2019-06-06
        • 1970-01-01
        • 2016-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多