Reputation: 585
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:
Upvotes: 3
Views: 3778
Reputation: 5083
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.
Upvotes: 2