首页 > 解决方案 > WPF Binding a collection of collections to a DataGrid

问题描述

To simplify my problem, let's say that I have a property, that I am binding my DataGrid to:

public List<LibrarySection> Library { get; set; }

Then in each LibrarySection I have

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

And book look like this:

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

Now how can I bind to property Library, to achieve in a DataGrid a list of all the books: Book table

标签: c#.netwpfxaml

解决方案


期望 LibrarySection 是DataContext您的 DataGrid 的,您可以简单地添加BooksItemsSource

如果AutoGenerateColumns设置true为此已经显示您的项目,但如果您想定义自己的列(更改标题和内容),您应该设置AutoGenerateColumns="false".

然后,您可以添加Columns并告诉每个对象绑定您要绑定的集合中包含Column的特定对象。PropertyItemsSource

<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>

通常你应该有ViewModel一个LibrarySection- 属性。如果是这样,只需使用ItemsSource="{Binding Library.Books}"

我还建议使用ObservableCollection<LibrarySection>andObservableCollection<Book>而不是,List<T>因为如果任何值发生变化,它会自动更新。


推荐阅读