Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Binding a collection of collections to a DataGrid

Tags:

c#

.net

wpf

xaml

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

like image 693
karollo Avatar asked Sep 16 '25 11:09

karollo


1 Answers

Expecting that LibrarySection is the DataContext of your DataGrid you can simply add Books as it's ItemsSource.

You if AutoGenerateColumns is set to true this already display your items but if you want to define your own columns (change headers and stuff) you should set AutoGenerateColumns="false".

You then can add Columns and tell each Column to bind a specific Property of the object contained in the collection your ItemsSource is binding to.

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

Normally you should have a ViewModel which has a LibrarySection-Property. If so simply use ItemsSource="{Binding Library.Books}"

I also recommend using ObservableCollection<LibrarySection> and ObservableCollection<Book> instead of List<T> since it automatically updated if any of the values change.

like image 99
Felix D. Avatar answered Sep 18 '25 08:09

Felix D.