WPF将一个集合中的多个集合绑定到DataGrid

3
为了简化我的问题,假设我有一个属性,我将我的DataGrid绑定到该属性上:
public List<LibrarySection> Library { get; set; }

然后每个LibrarySection中我都有:

class LibrarySection
{
   public string SectionName{ get; set; }
   public List<Book> Books { get; set; }
}

这是一本书的样子:

class Book
{
   public string Name { get; set; }
   public string Author { get; set; }
   public string BookID { get; set; }
}

现在我如何绑定属性Library,以便在DataGrid中获得所有书籍的列表:Book table
1个回答

1
期望LibrarySection是DataGrid的DataContext,您可以将Books添加为其ItemsSource。如果AutoGenerateColumns设置为true,则已经显示了您的项目,但是如果要定义自己的列(更改标题等),则应将AutoGenerateColumns设置为“false”。然后,您可以添加Columns并告诉每个Column绑定ItemsSource绑定的集合中包含的对象的特定Property。
<DataGrid ItemSource="{Binding Books}
          AutoGenerateColumns="false"><!--should be false-->
     <!-- Define custom columns -->
     <DataGrid.Columns>
          <DataGridTextColumn Binding="{Name}" Header="BookName" />
          <DataGridTextColumn Binding="{Author}" Header="Book Author" />
          <DataGridTextColumn Binding="{BookID}" Header="BookID" />             
      </DataGrid.Columns>
 </DataGrid>

通常情况下,您应该拥有一个具有LibrarySection属性的ViewModel。如果是这样,请使用ItemsSource="{Binding Library.Books}"
我还建议使用ObservableCollection<LibrarySection>ObservableCollection<Book>而不是List<T>,因为它会自动更新任何值发生更改。

谢谢 :) 是的,我有 ViewModel,但它没有 LiblarySection,而是一个名为 Library 的 List<LibrarySection>,正如我在问题中所述。此外,我同意应该使用 ObservableCollection<T>,但这不由我决定。 - karollo
1
您还可以使用 {Binding Library[0].Books} 绑定单个库 - 或者为每个库创建一个新的 DataGrid。从 WPF www.wpf-tutorial.com 和/或 www.wpftutorial.net 开始可能会非常有帮助。这些网站上有很多使用 DataGrid 的示例。对于您的情况,分组 也可能很有趣! - Felix D.
1
嘿,我有点误解你了。我没有时间仔细检查你的答案。我的网格的数据上下文是Library - List <LibrarySections>,而不是一个Library Section本身。我该如何将数据绑定到“Library”以获取书籍列表?我需要所有的LibrarySections都在同一个DataGrid中。 - karollo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接